Php Laravel-从另一个模型获取模型属性
类Php Laravel-从另一个模型获取模型属性,php,laravel,laravel-5,eloquent,Php,Laravel,Laravel 5,Eloquent,类ModelA与ModelB有关系belongsTo。有没有办法从ModelA访问该属性?比如: $this->model_b->model_b_attribute; 另外,是否有一种方法将模型链接到属性?如果我有belongsTo从ModelB到ModelC的关系,我可以这样做: $this->model_b->model_b_attribute->model_c; 编辑: 我的代码: ModelA将是: class LeaseTenant extends M
ModelA
与ModelB
有关系belongsTo
。有没有办法从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;
}
}
和modelbs
:
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();
}
}
# ModelA.php
public function modelB()
{
return $this->belongsTo(ModelA::class);
}
如果您在
ModelA
和ModelB
之间有关系,我想从LeaseTenant访问Rent
表:
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();
}
}
# ModelA.php
public function modelB()
{
return $this->belongsTo(ModelA::class);
}
然后还可以访问关系以获取ModelA
实例,从中可以访问ModelA
属性
$modelA = ModelA::find(1);
$name = $modelA->modelB->name;
// ^^^^^^ modelB attribute
此外,如果您在ModelB中有另一个belongsTo关系,则可以执行以下操作:
$name = ModelA::find(1)->modelB->modelC->name;
// ^^^^^^ modelC attribute
发布你的代码please@DiegoCespedes我不确定这会有什么帮助,但我已经发布了我的code@niksrb这很重要,因为它有助于理解您的实际问题。谢谢,我想在ModelA
中创建属性,以便从ModelC
访问ModelB
中的属性列。这是可能的!再次感谢您在您的leasereRequest
模型中,在getSecurityDepositoryAttribute()
方法内部的查询中,我认为根据property\u id
进行搜索是多余的,因为leasereRequest
似乎属于唯一的属性。现在,租金中使用的类型是静态类型,这是否适用于每个租赁请求
?如果是这样,您可以直接在LeaserRequest和Rent之间创建关系,而不是手动执行查询。但不管怎样,我很高兴能帮上忙。