SELECT(MAX)SQL以雄辩不生

问题描述 投票:0回答:1

我在我的迁移与雄辩,而不是SQL脚本在我的公司。

我想这样做与雄辩这个简单的查询,但我不知道该怎么做。

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      |
+--------------------------+

经过多次搜索,以雄辩被通知的方法是:

    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)简单Eloquent,不使用selectRaw()

php mysql sql select eloquent
1个回答
0
投票

随着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

在我来说,我不能用这个版本照亮,因为从5.5版本,你必须使用PHP 7。

© www.soinside.com 2019 - 2024. All rights reserved.