laravel - 在子查询中使用同一张表
问题描述
我无法将下一个 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']);
解决方案
你的查询应该是这样的(我不在电脑上测试这个,所以它可能需要进一步编辑)
$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']);
推荐阅读
- r - 具有未知长度变量列表的 R 函数
- android - 获取响应头
- python - 是否可以在 PyGame 中重置计时器?
- google-apps-script - Google OAuth2 范围 script.external_request 允许访问哪些用户数据?
- r - as.numeric() 为应该是数字的内容生成 NA
- docker - Docker-compose 与 nginx 反向,一个网站和一个宁静的 api?
- css - 更换时 SVG 背景抖动
- python - 从熊猫数据框中的单个单元格字符串创建新行
- javascript - 使用 JavaScript 自动点击按钮
- android - smsManager 不发送短信,也没有在应用程序中请求权限,尽管我已在代码中请求