mysql - 使用查询构建器在 laravel 预加载上使用 whereRaw 条件

标签 mysql sql laravel eloquent laravel-5

我们想要那些提示,通过 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/

相关文章:

SQL - 链接到更多表信息

Mysql 选择行并限制不同列

mysql无法创建表errno 150

sql - 当我使用 CASE 将字段设置为 NULL 时,为什么 PostgreSQL 会提示类型?

c# - 我应该在使用多线程 SqlBulkCopy 插入数据时使用表锁吗

php - 如何在 Laravel 5 中捕获 ReflectionException?

mysql - 连接多个表以获取库存项目的集合

laravel - 如何使用模型类在 laravel 8 资源 Controller 中编辑、销毁和获取单个值?

php - 合并相似的数组,PHP 或 MySQL

php - 如何设置查询以将表中的所有列与我的文本进行比较