doushe2513 2014-12-11 09:12
浏览 46
已采纳

加入数据库和计数

I'm trying to list informations about a table and one of that information is how much cars an user has. I have two databases, one is users and the other is cars. The table cars has a column that is owner that holds the id of the owner. What I want to know is: How to list all users and along with that the total of cars that each user has?

$users = Users::all();

This code returns an array with all users, what I want is to pass the total of cars that each user has on the same $users variable. How can I do that? Is there a way to join the other table, count and then return or something like that?

@edit

I tried like this, but doesn't work:

$users = Users::join('cars', 'cars.owner', '=', 'users.id')->select(DB::raw('count(cars.car_id) as total'))->get();
  • 写回答

3条回答 默认 最新

  • doulan3436 2014-12-11 09:19
    关注

    You need the group by statemant:

    select users.name, count(*) as counter from users 
    join cars on ... group by users.name;
    

    Okay here in more Detail:

    You have to join the users table with the cars table. You do that, yes.

    Then you have to select one col from the user table and one count(*) as counter

    The trick is now, to "group by" the col from the users table. That matches all double user rows to one row and count how much cars one user has

    The select statement is:

    "select users.id, count(*) as counter from Users join Cars on cars.owner=users.id group by users.id"

    Thats all ... hope that help you

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)
编辑
预览

报告相同问题?

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

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

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

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

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

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

客服 返回
顶部