在Laravel上通过查询构建器使用whereRaw条件进行热切加载

时间:2018-06-26 18:01:17

标签: mysql sql laravel eloquent laravel-5.2

我们希望需要那些抱怨,即通过雄辩的关系,生存期(created_at-now())会更好,然后是抱怨生存期(存储在抱怨类型表中的生存期数量)。

01.complain表:

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

AND预设-> complain_type:

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

complain_type->预设:

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

抱怨与抱怨类型之间没有直接关系。

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

关系为抱怨->预设-> 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行上,我们需要访问抱怨(抱怨).created_at。

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

2 个答案:

答案 0 :(得分:1)

  

我们需要那些抱怨

您可以使用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());

答案 1 :(得分:1)

您可以使用whereHas()

$records = db_query(
  $dbconn_read,
  'SELECT * FROM Table WHERE one = ? AND two = ?',
  'ii', 1, 2
);