Php 计算现有ID';他在另一张桌子上-拉威尔
我在一个名为Php 计算现有ID';他在另一张桌子上-拉威尔,php,laravel,Php,Laravel,我在一个名为products的表中有两项,id分别为1和。有一个名为invite的表,其中包含产品的外键product\u id 在下面的控制器中,我试图计算invite表中存在的产品id的数量 乙二醇 如上所述,invite表中存在id1和2。这意味着总计数为2(尽管产品id2出现两次) 当我运行下面的代码时,我得到的计数是1,而不是2。请问,我遗漏了什么 NB:在这种情况下,我只是一个用户 public function dashboard() { $products = Produ
products
的表中有两项,id分别为1和。有一个名为invite
的表,其中包含产品的外键product\u id
在下面的控制器中,我试图计算invite
表中存在的产品id的数量
乙二醇
如上所述,invite表中存在id1和2
。这意味着总计数为2(尽管产品id2
出现两次)
当我运行下面的代码时,我得到的计数是1
,而不是2
。请问,我遗漏了什么
NB:在这种情况下,我只是一个用户
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'));
}
控制器
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>
{{count\u existing\u products}}
对于中的WHERE
子句,laravel使用特殊的WHERE()
方法传递数组,而不是字符串
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();
不需要使用内爆。可以使用where而不是where
Invite::whereIn('product_id',$get_products_id)
->where('user_id', Auth::user()- >id)->get()->count();
您还可以按user\u id
进行筛选,可能是这样吗?我还假设传递内爆字符串的工作方式与您预期的不一样。在where条件下也使用user\u id
,但上面的invite表的结构中没有显示user\u id
。@u\u mulder,在这种情况下,我只使用了一个用户。请检查更新pleas@LovepreetSingh、 请检查更新一项建议,您可以使用$products->PULL('id')->此$get_products_id=[];foreach($products as$product){$get_products_id[]=$product->id;}@因此,LovePreetigh OP需要2
,而不是表数据中的3
。您仔细阅读了一个问题吗?@LovePreetigh,因为过滤是通过WHERE IN
WHERE product id1
和2
完成的。