繁体   English   中英

Laravel 模型连接四个表,条件和按日期分组

[英]Laravel model join four tables with condition and group by date

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

我想获取status_id2requests ,并加入在technology_task数据透视表中插入了特定technologiestasks表。 我想根据日期列created_at对结果进行分组。 这可能通过 Lravel 模型雄辩吗? 我试过下面的方法。

$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模型,它将返回status_id2所有请求以及相关的tasktechnologies 但是我只想要task具有特定technologiesrequests ,并且我想使用诸如->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 在分组时应选择哪些数据。 您可以使用聚合函数来实现这一点。 您不清楚要选择的数据,下面的代码应该返回:

  • 分组行的最大 id,
  • 与空格连接的独特评论
  • 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();

查看文档以了解每个聚合函数的工作原理。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM