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

如何将我的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()

图片转代码服务由CSDN问答提供 功能建议

我是laravel 5的新手如何将此查询转换为laravel ORM

 选择`users` .id`,`users` .username`,count(`ord` .id`)作为总
FROM`users` 
LEFT JOIN`order`AS`ord`  ON`ord``empolyee_id` =`users` .id` 
AND DATE(`ord` .created_at`)= $ date 
GROUP BY`users` .id` 
   
 
 

我尝试了这个解决方案,但它无法正常工作

  $ orders = Order :: rightjoin('users',function($ join)  use($ date){
 $ join-> on('users.id','=','orders.empolyee_id'); 
 $ join-> on(“DATE(created_at)”,'=  ',$ date); 
})
  - >选择(DB :: raw('count(orders.id)为total,users.username'))
  - > groupBy('users.id'  ) - > get()
   
 
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doujiao6872888 2015-05-20 21: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')
    
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题