如何使用表连接数组(数组中的链接ID与表ID)

时间:2017-02-26 17:46:26

标签: php mysql arrays laravel join

所以,我有一个包含列表的数据库。列表中的项目附有user_id,我已经完成了一个查询来计算它们并对它们进行分组,但是因为我在DB::Select和原始SQL中完成了从user_id到实际的关系用户已经迷路了。

我一直尝试加入,但到目前为止没有运气,这是我的代码:

这会让我看到包含number(count)user_id

的列表
$updatedToday = DB::select('SELECT user_id, COUNT(*) AS `num` FROM faulty_device WHERE DATE(`updated_at`) = DATE(CURDATE()) AND user_id IS NOT NULL AND (status = 3 OR status = 4 OR status = 5) GROUP BY user_id');

这不起作用,请参阅我尝试加入:

$updatedToday = DB::select('SELECT user_id, COUNT(*) AS `num` FROM faulty_device JOIN users ON faulty_device.user_id=users.id WHERE DATE(`updated_at`) = DATE(CURDATE()) AND user_id IS NOT NULL AND (status = 3 OR status = 4 OR status = 5) GROUP BY user_id');

我想要做的基本上是在我看来使用它:

@foreach($updatedToday as $updated)
    {{$updated->user->username}}
    {{$updated->num}}
@endforeach

(显示用户名:Ted Swansson,编号:15)

但到目前为止,我只能设法让它发挥作用:

@foreach($updatedToday as $updated)
    {{$updated->user_id}}
    {{$updated->num}}
@endforeach

(显示etc user_id:5,num:15)

关于如何解决这个问题的任何想法?

修改

我让它在phpmyadmin中工作,但同样的命令在laravel中失败....

SELECT user_id, username, COUNT(*) AS `num` FROM faulty_device JOIN users ON faulty_device.user_id=users.id WHERE DATE(`updated_at`) = DATE(CURDATE()) AND user_id IS NOT NULL AND (status = 3 OR status = 4 OR status = 5) GROUP BY user_id

说:

  

语法错误或访问冲突:1055' database1.users.username'   不在GROUP BY中(SQL:SELECT user_id,username,COUNT(*)AS num   FROM faulty_device JOIN用户ON faulty_device.user_id = users.id WHERE   DATE(updated_at)= DATE(CURDATE())AND user_id IS NOT NULL AND   (status = 3 OR status = 4 OR status = 5)GROUP BY user_id)

编辑2 Laravel想要一个额外的GROUP BY,它现在已经解决了。

1 个答案:

答案 0 :(得分:0)

想出来。它最后想要一个“用户名”作为附加的GROUP BY。

SELECT user_id, username, COUNT(*) AS `num` FROM faulty_device LEFT JOIN users ON faulty_device.user_id=users.id WHERE DATE(`updated_at`) = DATE(CURDATE()) AND user_id IS NOT NULL AND (status = 3 OR status = 4 OR status = 5) GROUP BY user_id, username