我们想要那些提示,通过 Eloquent 关系,哪个生命周期(created_at - now())比提示生命周期(存储在 complain_type 表中的生命周期数量)更重要。
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 |
+---+------------+
the relation between complain->preset is:
public function preset()
{
return $this->belongsTo(ComplainPreset::class, 'complain_preset_id');
}
the relation between preset->complain is:
public function complains()
{
return $this->hasMany(Complain::class, 'complain_id');
}
AND preset->complain_type:
public function complainType()
{
return $this->belongsTo(ComplainType::class, 'type_id');
}
complain_type->preset:
public function presets()
{
return $this->hasMany(ComplainPreset::class);
}
它们与 complaint 和 complain_type 没有直接关系。
这是我们 Eloquent 查询解决方案。但该查询不起作用。
关系是complain->preset->complain_type
Complain::with(['preset' => function ($q) {
$q->with(['complainType' => function($q2) {
$q2->whereRaw('SUBTIME(NOW(), lifetime) > complains.created_at');
}]);
}])->whereDate('created_at', '=' , Carbon::today());
在第 3 行,这个查询没有得到 complains.created_at,因为这一行引用了 complain_type 表。 在第 3 行,我们需要访问 complains.created_at。
他们有什么 Eloquent 方式吗?
最佳答案
您可以使用 whereHas()
:
Complain::whereHas('preset.complainType', function($query) {
$query->whereRaw('SUBTIME(NOW(), lifetime) > complains.created_at');
})->whereDate('complains.created_at', '=', Carbon::today());
关于mysql - 使用查询构建器在 laravel 预加载上使用 whereRaw 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51048999/