Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return Eloquent Relationship Dependent on Value of Field in Model

Say I have a Model, and I want to return a relationship, but it depends on a value of an attribute of the model. 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 relationship fine, however when I try to eager load, and call with('paymentType'), I get the exception Call to a member function addEagerConstraints() on null

like image 845
Ben Avatar asked Sep 17 '15 18:09

Ben


1 Answers

I would imagine that your issue with eager loading arises because the models are not yet populated with values. Trying to check for a model's type with $this->type goes against the nature of eager loading.

You options are to:

A) Use lazy loading so that type is populated in the model before you call the relationship, or

B) Use eager loading constraints

like image 64
Kevin Lee Avatar answered Oct 02 '22 23:10

Kevin Lee