[英]How to make a scope with a raw SQL query in Laravel 7?
我正在尝试使用此SQL查询在我的model中创建 scope:
SELECT *
FROM ro_container_events
WHERE (container_id, location_timestamp, id)
IN (
SELECT distinct container_id, MAX(location_timestamp) AS lts, MAX(id) AS rce_id
FROM ro_container_events
GROUP BY container_id
)
model 名称是ContainerEvent ,我数据库中的表名称是ro_container_events 。
另外,我知道 SQL 查询是有效的,因为我在我的 MySQL 管理工具 (HeidiSQL) 中运行了它,它返回了好的行。
我的 scope(在我的ContainerEvent模型中)目前看起来像这样:
public function scopeLatestEventForContainers($query)
{
return $query->select(DB::raw('
SELECT *
FROM ro_container_events
WHERE (container_id, location_timestamp, id)
IN (
SELECT distinct container_id, MAX(location_timestamp) AS lts, MAX(id) AS rce_id
FROM ro_container_events
GROUP BY container_id
)'
)
);
}
但它不返回任何行?
我一直在搜索这个主题,但似乎找不到我的 scope 有什么问题......
Laravel 文档说我们可以使用:
DB::raw('...')
为了进行具体的 SQL 查询。
而且我在其他一些线程上看到我应该能够使用以下内容制作 scope:
return $query->select(DB::raw('...');
尝试 Eloquent:
//as your where in select this must return just one row with 3 field
$in = ContainerEvent::distinct('container_id', 'location_timestamp', 'id')->where(fn($q) => {
'id' => ContainerEvent::max('id')
'location_timestamp' => ContainerEvent::max('location_timestamp')
])->get();
但这可能是错误的,因为 db 结构有野心。
我只是使用 Laravel 查询生成器尝试您的 SQL 语法,结果使用方法toSql()
返回您需要的确切内容。
SELECT * FROM ro_container_events WHERE (container_id, location_timestamp, id) IN (
SELECT distinct container_id, MAX(location_timestamp) AS lts, MAX(id) AS rce_id
FROM ro_container_events
GROUP BY container_id
)
试试这个 function:
public function scopeLatestEventForContainers($query)
{
return $query->whereIn(\DB::raw('(container_id, location_timestamp, id)'), function ($q) {
$q->distinct()->select(\DB::raw('
container_id,
MAX(location_timestamp) AS lts,
MAX(id) AS rce_id FROM `ro_container_events`
'))->groupBy('container_id');
});
}
希望这有帮助:)
最好的,vreedom18
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.