回归雄辩关系依赖于模型中的场域价值

时间:2022-10-15 22:33:31

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

当我有一个模型的实例时,我可以调用这种关系,但是当我尝试加载,并使用('paymentType')调用时,我得到异常调用一个成员函数addEagerConstraints()on null

1 个解决方案

#1


1  

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.

我会想象你出现了急切加载的问题,因为模型还没有填充值。尝试使用$ this-> type检查模型的类型违背了急切加载的性质。

You options are to:

您可以选择:

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

A)使用延迟加载,以便在调用关系之前在模型中填充类型,或者

B) Use eager loading constraints

B)使用急切的加载约束

#1


1  

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.

我会想象你出现了急切加载的问题,因为模型还没有填充值。尝试使用$ this-> type检查模型的类型违背了急切加载的性质。

You options are to:

您可以选择:

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

A)使用延迟加载,以便在调用关系之前在模型中填充类型,或者

B) Use eager loading constraints

B)使用急切的加载约束