雄辩关系中的继承

时间:2019-01-18 15:47:08

标签: laravel-5

这是我的模特

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();
}

0 个答案:

没有答案
相关问题