lundi 20 mai 2019

Laravel - get model attribute from another model

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.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire