【问题标题】:Using whereRaw condition on laravel eager loading with query builder使用查询构建器在 laravel 急切加载上使用 whereRaw 条件
【发布时间】:2018-12-05 12:51:43
【问题描述】:

我们希望需要那些抱怨,通过雄辩的关系,哪个生命周期(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');
}

preset->complain 的关系是:

public function complains()
{
    return $this->hasMany(Complain::class, 'complain_id');
}

AND 预设->complain_type:

public function complainType()
{
    return $this->belongsTo(ComplainType::class, 'type_id');
}

complain_type->预设:

public function presets()
{
    return $this->hasMany(ComplainPreset::class);
}

它们与抱怨类型没有直接关系。

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

关系是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 行中,此查询没有得到抱怨.created_at,因为此行引用了抱怨类型表。 在第 3 行,我们需要访问complains.created_at。

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

【问题讨论】:

  • 是过滤Complain数据还是只过滤Eager加载的数据?
  • 我们要过滤complain数据@MKhalidJunaid
  • 我们想要返回这个查询,因为我们稍后会添加一些其他 where 条件用于其他过滤。

标签: mysql sql laravel eloquent laravel-5.2


【解决方案1】:

你可以使用whereHas():

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

【讨论】:

    【解决方案2】:

    我们需要那些抱怨

    您可以使用连接来应用过滤器,使用主表complains 的列与您间接(通过抱怨预置)相关的表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());
    

    【讨论】:

    • 非常感谢,也许这可以解决我们的问题,但是这个问题有什么雄辩的解决方案吗?
    猜你喜欢
    • 2018-07-03
    • 2016-09-06
    • 2018-02-20
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 2020-08-11
    相关资源
    最近更新 更多