首页 > 解决方案 > 有条件的,基于另一个模型的价值

问题描述

我有三个模型

发票

工作室

R_studio_pay

关系如下

工作室有很多发票

工作室有一个R_studio_pay

如果 R_studio_pay 中的列 is_r 为 1,我需要获取发票->where('recurring', 'single')->get() 否则我不想要 where 子句。

我尝试使用 whereHas studio-> wherehas R_studio_pay 但有条件的 where 无法完成。

$invoices = invoice::with('studio')->whereHas('studio', function($query) {
   $query->whereHas('r_studio_pay', function($query) {
       $query->where('is_r', 1);
   });
})->where('recurring', 'single')

但不能在 where 条件下应用。

标签: phplaraveleloquenteloquent-relationship

解决方案


你在正确的轨道上。但是,您应该在回调中添加一个 return 语句。return $query->where('is_r', 1);而不是$query->where('is_r', 1);. 试试下面的代码。

$invoices = invoice::with('studio')->whereHas('studio', function($query){
   return $query->whereHas('r_studio_pay', function($query){
       return $query->where('is_r', 1);
   });
})->where('recurring', 'single');

推荐阅读