在查询生成器中使用laravel eager加载的whereraw条件

mklgxw1f  于 2021-06-24  发布在  Mysql
关注(0)|答案(2)|浏览(344)

我们希望的是需要那些投诉,其中生存期(created_at-now())比投诉生存期(存储在投诉类型表中的生存期数量)更大。
01.投诉表:

  1. +---+------------+-----------------+
  2. |id | complain_preset_id | created_at |
  3. +---+------------+-----------------+
  4. | 1 | 48 | 3/16/2018 10:30 |
  5. | 2 | 13 | 3/16/2018 10:43 |
  6. | 3 | 12 | 3/16/2018 10:57 |
  7. +---+------------+-----------------+

2投诉预置表:

  1. +---+------------+-----------------+
  2. |id | type_id | created_at |
  3. +---+------------+-----------------+
  4. | 1 | 1 | 3/16/2018 6:29 |
  5. | 2 | 2 | 3/16/2018 6:29 |
  6. | 3 | 3 | 3/16/2018 6:29 |
  7. +---+------------+-----------------+

3投诉类型表

  1. +---+------------+
  2. |id | lifetime |
  3. +---+------------+
  4. | 1 | 10 |
  5. | 2 | 36 |
  6. | 3 | 360 |
  7. | 4 | 500 |
  8. +---+------------+

投诉->预设的关系是:

  1. public function preset()
  2. {
  3. return $this->belongsTo(ComplainPreset::class, 'complain_preset_id');
  4. }

预设->投诉之间的关系是:

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

和预设->U类型:

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

单击类型->预设:

  1. public function presets()
  2. {
  3. return $this->hasMany(ComplainPreset::class);
  4. }

他们之间没有直接的关系,投诉投诉类型。
这是我们的解决方案,有说服力的质疑。但这个查询不起作用。
关系为投诉->预置->投诉类型

  1. Complain::with(['preset' => function ($q) {
  2. $q->with(['complainType' => function($q2) {
  3. $q2->whereRaw('SUBTIME(NOW(), lifetime) > complains.created_at');
  4. }]);
  5. }])->whereDate('created_at', '=' , Carbon::today());

在第3行中,此查询没有获取complains.created\u at,因为此行引用了complaint\u type表。在第3行,我们需要访问complains.u at。
他们有什么雄辩的方法吗?

xv8emn3q

xv8emn3q1#

我们需要那些抱怨
您可以使用join来使用主表的列应用筛选器 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());

ct3nt3jp

ct3nt3jp2#

你可以用 whereHas() :

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

相关问题