dongxuan58311366668 2019-02-01 09:51
浏览 51
已采纳

SELECT(MAX)SQL到Eloquent没有原始

I'm migrating my scripts with Eloquent instead of SQL in my company.

I want to do this simple query with Eloquent, but I don't know how to do that.

SQL QUERY :

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

After several searches, the method with Eloquent that advised is:

    MyModel::orderBy('date', 'desc')->groupBy('id')->where('people', '>', 0);

But the result is not (and it's normal...) the same :

+--------------------------+
|    date    |     ID      |
+--------------------------+
| 2012-06-25 |     79      |
| 2012-06-25 |     56      |
| 2012-06-25 |     55      |
+--------------------------+

I would simply like to know if it's possible to do a simple SELECT(MAX) with Eloquent, without using selectRaw()

  • 写回答

1条回答 默认 最新

  • drl57959 2019-02-05 10:34
    关注

    With illuminate/database v5.4 it's not possible without using raw() methods like :

    • selectRaw(),
    • whereRaw(),
    • ....
    • or with facade DB::raw()

    With illuminate/database v5.7 you can do sub-queries in a leftJoin() for example, like :

    $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();
    

    See: https://laravel.com/docs/5.7/queries

    In my case I can not use this version of illuminate, because from version 5.5, you have to use php 7.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输