在 laravel 上使用 whereRaw 条件与查询构建器进行预加载

Using whereRaw condition on laravel eager loading with query builder

我们需要那些抱怨,生命周期(created_at - now()) 比抱怨生命周期(存储在 complain_type table 上的生命周期数量)要大 [= =59=]关系。

01.complain table:

+---+------------+-----------------+
|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。投诉预设Table:

+---+------------+-----------------+
|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。投诉类型table

+---+------------+
|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);
}

他们投诉到complain_type没有直接关系。

这是我们的解决方案 eloquent 查询。但该查询不起作用。

关系是抱怨->预设->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 table。 在第 3 行,我们需要访问 complains.created_at.

他们有什么eloquent方式吗?

We want's to need those complain

您可以使用 join 来应用过滤器,使用主 table complains 的列与间接(通过 complain_preset)相关的 table complain_type

Complain::with('preset')
        ->join('complain_preset as cs','complains.complain_preset_id','=', 'cs.id')
        ->join('complain_type as ct','cs.type_id','=', 'ct.id')
        ->whereRaw('SUBTIME(NOW(), ct.lifetime) > complains.created_at')
        ->whereDate('complains.created_at', '=' , Carbon::today());

您可以使用 whereHas():

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