首页 > 解决方案 > 在子查询中使用同一张表

问题描述

我无法将下一个 SQL 代码转换为 laravel eloquent:

SELECT t1.template, t1.created_at
FROM sent_emails t1
where created_at = (
    select max(created_at) from sent_emails t2 where t2.template = t1.template
)
group by t1.created_at, t1.template

或者:

SELECT t1.template, t1.created_at
FROM sent_emails t1
JOIN 
(
    SELECT Max(created_at) date, template
    FROM   sent_emails 
    GROUP BY template 
) AS t2 
    ON t1.template = t2.template
    AND t1.created_at = t2.date
group by t1.created_at, t1.template

两个查询都返回相同的数据集。在单独的变量中创建子查询不是一种选择,因为我需要从中返回多个值。

如果我使用模型(而不是使用)创建表,我也不知道如何设置别名DB::,所以这是我不成功的尝试:

$sent_emails = SentEmail::where('created_at', function($query) {
            SentEmail::where('template', 't1.template')->orderBy('created_at', 'desc');
        })->groupBy('template', 'created_at')->get(['template', 'created_at']);

标签: laraveleloquentlaravel-query-builder

解决方案


你的查询应该是这样的(我不在电脑上测试这个,所以它可能需要进一步编辑)

$sent_emails = SentEmail::where('created_at', function($query) {
            $query->where('created_at', SentEmail::->whereColumn('column_name', 'table.column_name')->orderBy('created_at', 'desc')->max('created_at'));
        })->groupBy('template', 'created_at')->get(['template', 'created_at']);

推荐阅读