Class ModelA has relationship belongsTo to ModelB. Is there any way to access that attribute from ModelA? Something like:
$this->model_b->model_b_attribute;
Also, is there a way to chain model to attribute? If I have belongsTo relationship from ModelB to ModelC could I do this:
$this->model_b->model_b_attribute->model_c;
Edit:
My code:
ModelA would be:
class LeaseTenant extends Model {
protected $appends = ['is_deposit_paid'];
public function lease_request()
{
return $this->belongsTo('App\Models\LeaseRequest');
}
public function getIsDepositPaidAttribute()
{
return $this->email == $this->lease_request->security_deposit_entry->bank_account->user->email;
}
}
And ModelB:
class LeaseRequest extends Model {
protected $appends = ['security_deposit_entry'];
public function getSecurityDepositEntryAttribute()
{
return Rent
::where('property_id', $this->property_id)
->where('lease_request_id', $this->id)
->where('type', 'security_deposit')
->orderBy('created_at', 'asc')->first();
}
}
I want to access Rent table from LeaseTenant.
ModelAto access column fromModelCover attribute fromModelB. And it is possible! Thanks agaubLeaseRequestmodel, on the query inside yourgetSecurityDepositEntryAttribute()method I think that search byproperty_idis redundant given the fact that theLeaseRequestseems to belong to a uniqueProperty. Now, the type used in the Rent is a static one, does this will apply for everyLeaseRequest? If so, you could create a relationship directly between LeaseRequest and Rent instead of doing the query manually. But anyway, I'm glad I could help.