亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Laravel - 從另一個模型獲取模型屬性

Laravel - 從另一個模型獲取模型屬性

PHP
牛魔王的故事 2021-06-22 17:01:03
類ModelA有關系belongsTo到ModelB。有沒有辦法從 訪問該屬性ModelA?就像是:$this->model_b->model_b_attribute;另外,有沒有辦法將模型鏈接到屬性?如果我有belongsTo從ModelB到的關系,ModelC我可以這樣做:$this->model_b->model_b_attribute->model_c;編輯:我的代碼:ModelA 將會: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;        }}并且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();    }}我想Rent從LeaseTenant.
查看完整描述

1 回答

?
千萬里不及你

TA貢獻1784條經驗 獲得超9個贊

如果您belongsTo在ModelA和之間有關系ModelB:


# ModelA.php


public function modelB()

{

    return $this->belongsTo(ModelA::class);

}

然后您還可以訪問關系以獲取ModelA實例,您可以從中訪問ModelA屬性。


$modelA = ModelA::find(1);

$name = $modelA->modelB->name;

//                      ^^^^^^ modelB attribute

此外,如果您在 ModelB 中還有另一個屬于關系,您可以這樣做:


$name = ModelA::find(1)->modelB->modelC->name;

//                                      ^^^^^^ modelC attribute


查看完整回答
反對 回復 2021-06-25
  • 1 回答
  • 0 關注
  • 265 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號