这是我的模特
class Company extends Model {
// attributes:
// payment_method_id - not nullable
// ...
public function paymentMethod(){
return $this->belongsTo('App\Models\PaymentMethod');
}
}
class Location extends Model {
// attributes:
// company_id
// payment_method_id - nullable
// ...
public function company(){
return $this->belongsTo('App\Models\Company');
}
public function paymentMethod(){
return $this->belongsTo('App\Models\PaymentMethod');
}
public function getPaymentMethodAttribute($value){
return $value ?? $this->company->payment_method;
}
}
我希望在getPaymentMethodAttribute
模型中将Location
动态属性转换为雄辩的关系。
因此,我想在Location
模型上得到如下结果:
public function paymentMethod(){
// give me the location payment_method and if none, give me the company paymentMethod
}
编辑
我已经做了一些努力,但是如果paymentMethod
没有Location
,我只能从Company
获得一个 collection ,不是模型-我需要:
public function companyPaymentMethod(){
return $this->hasManyThrough('App\Models\PaymentMethod', 'App\Models\Company','id','id','company_id','payment_method_id');
}
public function locationPaymentMethod(){
return $this->belongsTo('App\Models\PaymentMethod','payment_method_id');
}
public function paymentMethod(){
return $this->locationPaymentMethod ? $this->locationPaymentMethod() : $this->companyPaymentMethod();
}