Laravel model 将四个表按条件和分组按日期连接起来

Laravel model join four tables with condition and group by date

我有四个table technologies(id, name), tasks(id, name), requests(id, status_id, comment, task_id, created_at), technology_task(id, task_id, technology_id)

我想获取 status_id2requests 并加入其中插入了特定 technologiestasks table technology_task 枢轴 table。我想根据日期列 created_at 对结果进行分组。这可以通过 Lravel 模型 eloquent 实现吗?我试过下面的方法。

$this->model
        ->with('task', 'task.technologies')
        ->where('status_id', 2)->get()
        ->groupBy(function ($val) {
            return Carbon::parse($val->created_at)->format('d-m-Y')

这是 Request 模型,这将 return 所有 status_id2 的请求以及相关的 tasktechnologies.但我只想要 requeststask 具有特定的 technologies,并且我想使用 ->whereIn('id', [1, 2, 3])->get() 之类的东西来检查它 如何实现这个使用模型?还是我需要使用自定义查询

假设 $this->model 是您的 Request 模型,并且您的所有关系都设置正确,您可以使用 whereHas:

$technologyIds = [1, 2, 3];

$collection = $this->model
    ->with(['task', 'task.technologies'])
    ->whereHas('task.technologies', function($query) use ($technologyIds)
    {
        // here you can check using whereIn
        $query->whereIn('technologies.id', $technologyIds);
    })
    ->where('requests.status_id', 2)
    ->get();

如果要在 MySQL 查询中使用 groupBy,则需要定义分组时应该 MySQL select 的数据。您可以使用 aggregation functions 来实现。您不清楚要select的数据,下面的代码应该return:

  • 分组行的最大id,
  • 与 space
  • 连接的独特评论
  • created_at
$technologyIds = [1, 2, 3];

$collection = $this->model
    ->with('task', 'task.technologies')
    ->whereHas('task.technologies', function($query) use ($technologyIds)
    {
        $query->whereIn('technologies.id', $technologyIds);
    })
    ->where('requests.status_id', 2)
    ->groupBy('requests.created_at')
    ->selectRaw('
        MAX(requests.id) AS id,
        GROUP_CONCAT(DISTINCT requests.comment
                     ORDER BY requests.comment ASC SEPARATOR ' ') AS comments,
        requests.created_at
    ')
    ->get();

查看文档以了解每个 aggregation functions 的工作原理。