Returning eloquent relationships depending on the field value in the model

Say I have a model and I want to return the relationship, but it depends on the value of the model attribute. I tried this in my model:

public function paymentType(){
    if($this->type > 1) return $this->hasOne(PaymentType::class, 'type', 'type');
    if($this->type == 1) return $this->hasOne(PaymentType::class, 'payment_type', 'pay_type');
}

When I have an instance of the model, I can call this connection beautiful, however, when I try to load the load and call with('paymentType'), I get an exceptionCall to a member function addEagerConstraints() on null

+4
source share
1 answer

I would suggest that your eager loading problem arises because the models are not yet populated with values. Attempting to verify the type of model using $this->typeis contrary to the nature of impatient loading.

You can:

A) , type

B)

+1

Source: https://habr.com/ru/post/1607877/


All Articles