【问题标题】:Return Eloquent Relationship Dependent on Value of Field in Model返回依赖于模型中字段值的雄辩关系
【发布时间】:2015-09-18 05:23:46
【问题描述】:

假设我有一个模型,我想返回一个关系,但这取决于模型的属性值。我在我的模型中试过这个:

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

当我有模型的实例时,我可以很好地调用这种关系,但是当我尝试预先加载并调用 with('paymentType') 时,我得到异常 Call to a member function addEagerConstraints() on null

【问题讨论】:

  • 在使用paymentType() 关系的查询中是否有with() 调用?
  • 是的,我应该在我的问题中指出,当我有模型的实例时,该方法可以正常工作。但是,当我尝试加载关系 ->with('paymentType) 时,我得到了异常。已在我的问题中修复。

标签: php laravel eloquent


【解决方案1】:

我想您的急切加载问题会出现,因为模型尚未填充值。尝试使用 $this->type 检查模型的类型与预加载的性质背道而驰。

你的选择是:

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

B)Use eager loading constraints

【讨论】:

    猜你喜欢
    • 2013-04-10
    • 1970-01-01
    • 2019-02-12
    • 1970-01-01
    • 2017-07-29
    • 2013-06-04
    • 2016-11-26
    • 2018-02-19
    • 2019-04-18
    相关资源
    最近更新 更多