mysql - 使用查询生成器在 laravel 急切加载上使用 whereRaw 条件
问题描述
我们需要那些抱怨,通过雄辩的关系,哪个生命周期(created_at - now())比抱怨生命周期(存储在抱怨类型表上的生命周期数量)更重要。
01.投诉表:
+---+------------+-----------------+
|id | complain_preset_id | created_at |
+---+------------+-----------------+
| 1 | 48 | 3/16/2018 10:30 |
| 2 | 13 | 3/16/2018 10:43 |
| 3 | 12 | 3/16/2018 10:57 |
+---+------------+-----------------+
02.投诉预设表:
+---+------------+-----------------+
|id | type_id | created_at |
+---+------------+-----------------+
| 1 | 1 | 3/16/2018 6:29 |
| 2 | 2 | 3/16/2018 6:29 |
| 3 | 3 | 3/16/2018 6:29 |
+---+------------+-----------------+
03.投诉类型表
+---+------------+
|id | lifetime |
+---+------------+
| 1 | 10 |
| 2 | 36 |
| 3 | 360 |
| 4 | 500 |
+---+------------+
抱怨->预设之间的关系是:
public function preset()
{
return $this->belongsTo(ComplainPreset::class, 'complain_preset_id');
}
预设->抱怨之间的关系是:
public function complains()
{
return $this->hasMany(Complain::class, 'complain_id');
}
和预设-> 投诉类型:
public function complainType()
{
return $this->belongsTo(ComplainType::class, 'type_id');
}
抱怨类型->预设:
public function presets()
{
return $this->hasMany(ComplainPreset::class);
}
他们与抱怨到抱怨类型没有直接关系。
这是我们的解决方案雄辩的查询。但该查询不起作用。
关系是抱怨->预设->抱怨类型
Complain::with(['preset' => function ($q) {
$q->with(['complainType' => function($q2) {
$q2->whereRaw('SUBTIME(NOW(), lifetime) > complains.created_at');
}]);
}])->whereDate('created_at', '=' , Carbon::today());
在第 3 行,这个查询没有得到抱怨.created_at,因为这一行引用了抱怨类型表。在第 3 行,我们需要访问complains.created_at。
他们有什么雄辩的方式吗?
解决方案
您可以使用whereHas()
:
Complain::whereHas('preset.complainType', function($query) {
$query->whereRaw('SUBTIME(NOW(), lifetime) > complains.created_at');
})->whereDate('complains.created_at', '=', Carbon::today());
推荐阅读
- html - 有带角材料的三态切换滑块吗?
- python-attrs - 大致比较用`attrs`定义的类的十进制属性
- html-email - 可以在 MJML 中加入伪元素吗?
- java - Spring Boot @RestController,在反序列化 @RequestBody 中的集合时可以容忍 MismatchedInputException
- nuget - 如何在 nuspec 中正确定义依赖关系
- javascript - 计算多个面板中选中复选框的数量,并使用 jQuery/JavaScript 在正确的面板中显示相关数字
- scala - Spark/Pyspark 中的 Scala 依赖项
- geoserver - GeoServer:最初登录时收到错误消息
- elixir - 将“配置变量”作为静态值的替代方法
- spring-boot - @PreAuthorization 与自定义 JWT 属性的比较