2016-07-16 28 views
0

我有以下查詢計數:Laravel:如何查詢

App\User::join('gift_sents', function($builder){ 
     $builder->on('gift_sents.receiver_id', '=', 'users.id'); 
     }) 
     ->select('users.*', 'COUNT(gift_sents.receiver_id as total_posts') 
     ->groupBy('gift_sents.id') 
     ->orderBy('total_posts', 'ASC') 
     ->limit(3)->get(); 

計數不工作,它應該是工作!

下面的錯誤出現:

Column not found: 1054 Unknown column 'COUNT(gift_sents.receiver_id' in 'field list' (SQL: select用戶.*, COUNT(gift_sents . receiver_id as TOTAL_POSTS from用戶inner join gift_sents on gift_sents . receiver_id =用戶. ID group by gift_sents . ID order by TOTAL_POSTS asc limit 3)

+0

您的SELECT語句中一個錯字,請務必關閉你的COUNT左括號。 ' - > select('users。*','COUNT(gift_sents.receiver_id as total_posts)')' –

+0

仍然無法使用! – Gammer

+1

錯誤:'未知的列'計數(gift_sents.receiver_id)'' – Gammer

回答

0

相反的:

->select('users.*', 'COUNT(gift_sents.receiver_id as total_posts') 

你應該使用:

->selectRaw('users.*, COUNT(gift_sents.receiver_id) as total_posts') 
3

我認爲這應該是:

->select('users.*', DB::raw('COUNT(gift_sents.receiver_id) as total_posts')) 

見文件here - '原始表達式' 部分

+0

是的,你是對的!需要一點編輯! – Gammer