首页 > 解决方案 > 使用查询生成器在 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。

他们有什么雄辩的方式吗?

标签: mysqlsqllaraveleloquentlaravel-5.2

解决方案


您可以使用whereHas()

Complain::whereHas('preset.complainType', function($query) {
    $query->whereRaw('SUBTIME(NOW(), lifetime) > complains.created_at');
})->whereDate('complains.created_at', '=', Carbon::today());

推荐阅读