[英]SQL Join with subquery counting number of records with the same id in a different table
[英]Counting Existing ID's in a different table - laravel
我在一個名為products
的表中有兩個項目,其ID為1 and 2
。 有一種稱為表invite
具有外鍵product_id
的products
。
在下面的控制器中,我試圖計算invite
表中現有產品ID的數量。
例如
Product invite
id name id token product_id user_id
1 cal 1 ..d 1 2
2 del 2 dd.. 2 2
3 mac 3 ..gh4 2 2
如上所述,邀請表中存在ID的1 and 2
。 表示總計數為2(盡管產品ID 2
出現了兩次。
當我在下面運行代碼時,我得到的計數是1
而不是2
。 請問我可能會錯過什么?
注意:在這種情況下,我只是一個用戶
調節器
public function dashboard()
{
$products = Products::orderBy('created_at', 'desc')
->where('user_id', Auth::user()->id)->get();
$get_products_id = [];
foreach($products as $product){
$get_products_id[] = $product->id;
}
$implode_data = implode(',',$get_products_id);
$count_existing_products =
Invite::where('product_id',$implode_data)
->where('user_id', Auth::user()- >id)->get()->count();
return view('dashboard', compact('count_existing_products'));
}
視圖
<h1>{{count_existing_products}}}</h1>
對於WHERE IN
子句,laravel使用特殊的whereIn()
方法來傳遞數組 ,而不是string 。 因此,您的查詢變為:
Invite::whereIn('product_id', $get_products_id)
->where('user_id', Auth::user()->id)
->distinct() // added `distinct` call to get distinct values
->get()
->count();
如果distinct
不起作用,請嘗試groupBy
:
Invite::whereIn('product_id', $get_products_id)
->where('user_id', Auth::user()->id)
->groupBy('product_id')
->get()
->count();
無需使用內爆。 您可以使用whereIn代替where。
Invite::whereIn('product_id',$get_products_id)
->where('user_id', Auth::user()- >id)->get()->count();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.