[英]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.