dsf12313 2015-05-20 12:31
浏览 130
已采纳

如何将我的sql查询中的join转换为laravel ORM

I'm new in laravel 5 how can i convert this query to laravel ORM

 select `users`.`id`, `users`.`username`, count(`ord`.`id`) As total 
FROM `users`
LEFT JOIN `orders` AS `ord`  ON `ord`.`empolyee_id` = `users`.`id`
AND  DATE(`ord`.`created_at`) = $date
GROUP BY `users`.`id`

I tried this solution but it didn't work correctly

 $orders = Order::rightjoin('users',function($join)  use($date){
        $join->on('users.id', '=','orders.empolyee_id');
        $join->on("DATE(created_at)", '=', $date);
    })
        ->select(DB::raw('count(orders.id) as total, users.username'))
        ->groupBy('users.id')->get()
  • 写回答

1条回答 默认 最新

  • 普通网友 2015-05-20 13:16
    关注

    Given you select only username and total, you probably want an array instead of eloquent results, that's why lists at the end. If you still want the collection of models, then use get instead.

    $users = User::leftJoin('orders as o', function($join) use ($date) {
          $join->on('users.id', '=', 'o.empolyee_id')
               ->where(DB::raw('DATE(o.created_at)'), '=', $date);
       })
       ->selectRaw('count(o.id) as total, users.username')
       ->groupBy('users.id')
       ->lists('total', 'username')
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部