類ModelA有關(guān)系belongsTo到ModelB。有沒有辦法從 訪問該屬性ModelA?就像是:$this->model_b->model_b_attribute;另外,有沒有辦法將模型鏈接到屬性?如果我有belongsTo從ModelB到的關(guān)系,ModelC我可以這樣做:$this->model_b->model_b_attribute->model_c;編輯:我的代碼:ModelA 將會(huì):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貢獻(xiàn)1784條經(jīng)驗(yàn) 獲得超9個(gè)贊
如果您belongsTo在ModelA和之間有關(guān)系ModelB:
# ModelA.php
public function modelB()
{
return $this->belongsTo(ModelA::class);
}
然后您還可以訪問關(guān)系以獲取ModelA實(shí)例,您可以從中訪問ModelA屬性。
$modelA = ModelA::find(1);
$name = $modelA->modelB->name;
// ^^^^^^ modelB attribute
此外,如果您在 ModelB 中還有另一個(gè)屬于關(guān)系,您可以這樣做:
$name = ModelA::find(1)->modelB->modelC->name;
// ^^^^^^ modelC attribute
- 1 回答
- 0 關(guān)注
- 256 瀏覽
添加回答
舉報(bào)
0/150
提交
取消