类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
- 1 回答
- 0 关注
- 244 浏览
添加回答
举报
0/150
提交
取消