doushe2513 2014-12-11 17: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 17: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条)

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 深度学习残差模块模型
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计
  • ¥23 (标签-bug|关键词-密码错误加密)