gpt4 book ai didi

左连接的 Laravel 排序结果

转载 作者:行者123 更新时间:2023-12-04 00:36:15 24 4
gpt4 key购买 nike

我正在尝试在 Laravel Eloquent 查询构建器中复制以下 SQL。

select a.name, b.note from projects a 
left join (select note, project_id from projectnotes order by created_at desc) as b on (b.project_id = a.id)
where projectphase_id = 10 group by a.id;

到目前为止,我有:
$projects = Project::leftjoin('projectnotes', function($join)
{
$join->on('projectnotes.project_id', '=', 'projects.id');
})
->where('projectphase_id', '=', '10')
->select(array('projects.*', 'projectnotes.note as note'))
->groupBy('projects.id')
->get()

除了获取最新的 projectnotes 之外,它适用于所有内容,它只返回输入到每个项目的 projectnotes 表中的第一个。

我需要通过 'created_at' desc 将订单放入左连接中,但我不知道如何实现。

任何帮助将非常感激。

最佳答案

您的子查询是不必要的,只会使整个事情效率低下。不过,可以肯定的是,请确保此查询返回相同的结果...

SELECT
projects.name,
notes.note
FROM
projects
LEFT JOIN
projectnotes notes on projects.id = notes.project_id
WHERE
projects.projectphase_id = 10
ORDER BY
notes.created_at desc

如果是这样,该查询转换为查询构建器看起来像这样......
$projects = DB::table('projects')
->select('projects.name', 'notes.note')
->join('projectnotes as notes', 'projects.id', '=', 'notes.project_id', 'left')
->where('projects.projectphase_id', '=', '10')
->orderBy('notes.created_at', 'desc')
->get();

关于左连接的 Laravel 排序结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24206872/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com