laravel group by with null value

时间:2018-03-08 11:12:20

标签: php laravel

我想通过电子邮件发送一个小组并从该记录中返回最新消息。该字段可以为null

这是我的表结构是

full_name  |  email        | mobile | created_date
   van      | van@mail.com  | +1.... | 2018-03-07
   van L    | van@mail.com  | +12... | 2018-03-08
            |               | +11... | 2018-03-07
            |               | +11... | 2018-03-08

我希望输出为

full_name |  email        | mobile | created_date
            |               | +11... | 2018-03-08
   van L    | van@mail.com  | +12... | 2018-03-08
            |               | +11... | 2018-03-07

我的代码是

$byMobile =  User::Where('email',null)
         ->pluck('id','id')->toArray()

$byEmail = User::groupBy('email')
                ->orderByRaw("id DESC, created_at DESC")
                ->pluck('id','id')->toArray();

$user_ids = array_merge($byMobile, $byEmail);

$messageRequest = User::whereIn('id',$user_ids)
                    ->latest()->get();

任何人都可以给我最好的方法或查询。我试过但我没有得到正确答案..帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

您可以使用类似的东西

$byMobile   =   User::whereNull('email');

$messageRequest = User::whereNotNull('email')
                        ->union($byMobile)
                        ->groupBy('email')
                        ->orderByRaw("id DESC, created_at DESC")
                        ->get();

对我来说我遇到了同样的问题。