php - SELECT(MAX) SQL 到没有原始的 Eloquent
问题描述
我在公司中使用 Eloquent 而不是 SQL 迁移我的脚本。
我想用 Eloquent 做这个简单的查询,但我不知道该怎么做。
SQL查询:
SELECT MAX(date), id
FROM myTable
WHERE people > 0
GROUP BY id
+--------------------------+
| date | ID |
+--------------------------+
| 2012-08-04 | 79 |
| 2013-04-13 | 56 |
| 2013-04-13 | 55 |
+--------------------------+
经过多次搜索,建议使用 Eloquent 的方法是:
MyModel::orderBy('date', 'desc')->groupBy('id')->where('people', '>', 0);
但结果不一样(这很正常......):
+--------------------------+
| date | ID |
+--------------------------+
| 2012-06-25 | 79 |
| 2012-06-25 | 56 |
| 2012-06-25 | 55 |
+--------------------------+
我只是想知道是否可以在不使用的情况下做一个简单SELECT(MAX)
的 withEloquent
selectRaw()
解决方案
illuminate/database v5.4
如果不使用以下方法是不可能的raw()
:
selectRaw()
,whereRaw()
,- ……
- 或与门面
DB::raw()
例如,illuminate/database v5.7
您可以执行子查询leftJoin()
,例如:
$latestPosts = DB::table('posts')
->select('user_id', DB::raw('MAX(created_at) as last_post_created_at'))
->where('is_published', true)
->groupBy('user_id');
$users = DB::table('users')
->joinSub($latestPosts, 'latest_posts', function ($join) {
$join->on('users.id', '=', 'latest_posts.user_id');
})->get();
请参阅:https ://laravel.com/docs/5.7/queries
就我而言,我不能使用这个版本的Illuminate,因为从5.5版本开始,你必须使用php 7。
推荐阅读
- ios - 如何使用特定阈值过滤器快速录制音频
- php - symfony/profiler-pack 在安装后立即被删除
- google-cloud-platform - 我不想为外部用户生成服务帐户,我想与之共享 bigquery 数据集 - 这会产生什么影响?
- amazon-sns - 无法接收来自 SNS 的消息
- objective-c - SwiftUI 小部件:在导入的 Objective-C 头文件中的 UILabel 参数上出现“预期类型”错误
- node.js - EJS 和条件语句
- libreoffice - 在行中查找最后填充的条目
- c - 回调函数与 C 中的 void 表达式有问题?
- angular - 当我单击子组件的输入时,会显示一个 div,我怎样才能一次制作一个或隐藏其他?
- c# - C# .NetCore HttpClient PostAsync Multipart Form-Data,带有文件附件和进度,供 PowerShell 使用