2017-02-26 90 views
0

所以,我有一個數據庫與列表。列表中的項目有一個user_id附加到他們,我已經做了一個查詢來計數和分組他們,但因爲我已經在DB::Select和原始SQL中執行此操作,從user_id到實際用戶的關係已經丟失。如何連接數組與表(鏈接ID與數組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 

(顯示等USER_ID:5民: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 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)

EDIT 2 Laravel想附加GROUP BY,現在已得到解決。

+0

不應該'SELECT user_id,COUNT(*)AS num'包含'username'嗎?也許可能使用左連接? – frz3993

+0

那麼,用戶名是在另一個表中,所以當前唯一被列出的是user_id和num。將檢查這個左連接。 – Stoff

+0

左連接返回沒有更多atm,可能是做錯了tho ..仍然得到: 數組:6 [▼ 0 => {#427▼ + 「USER_ID」:1 + 「NUM」:2 } 1 => {#187▼ + 「USER_ID」:3 + 「NUM」:3 } 2 => {#429▼ + 「USER_ID」:13 + 「NUM」:8 } 3 => {#428▼ + 「USER_ID」:14 +」 NUM 「:5 } 4 => {#432▼ +」 USER_ID 「:16 +」 NUM「:4 } 5 => {#433▼ +「user_id」:27 +「num」:30 } ] – Stoff

回答

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