[英]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_id
为2
的requests
,并加入在technology_task
数据透视表中插入了特定technologies
的tasks
表。 我想根据日期列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_id
为2
所有请求以及相关的task
和technologies
。 但是我只想要task
具有特定technologies
的requests
,并且我想使用诸如->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 在分组时应选择哪些数据。 您可以使用聚合函数来实现这一点。 您不清楚要选择的数据,下面的代码应该返回:
$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.