首页 > 解决方案 > 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)的 withEloquentselectRaw()

标签: phpmysqlsqlselecteloquent

解决方案


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。


推荐阅读