简体   繁体   English

计算不同表中的现有ID-Laravel

[英]Counting Existing ID's in a different table - laravel

I have two items in a table called products with id's 1 and 2 . 我在一个名为products的表中有两个项目,其ID为1 and 2 There is a table called invite which has foreign key product_id for products . 有一种称为表invite具有外键product_idproducts

In my controller below, i am trying to count the number of product id's that is existing in the invite table. 在下面的控制器中,我试图计算invite表中现有产品ID的数量。

eg 例如

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

As above, id's 1 and 2 exist in the invite table. 如上所述,邀请表中存在ID的1 and 2 meaning the total count is 2 (although product id 2 appears twice. 表示总计数为2(尽管产品ID 2出现了两次。

When i run my code below, i get a count of 1 instead of 2 . 当我在下面运行代码时,我得到的计数是1而不是2 What could i be missing out, please? 请问我可能会错过什么?

NB: in this case, i am user just one user 注意:在这种情况下,我只是一个用户

Controller 调节器

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'));

}

View 视图

<h1>{{count_existing_products}}}</h1>

For WHERE IN clause laravel uses special whereIn() method where you pass array , not string . 对于WHERE IN子句,laravel使用特殊的whereIn()方法来传递数组 ,而不是string So, your query becomes: 因此,您的查询变为:

Invite::whereIn('product_id', $get_products_id)
    ->where('user_id', Auth::user()->id)
    ->distinct()         // added `distinct` call to get distinct values
    ->get()
    ->count();

If distinct does not work, try to groupBy : 如果distinct不起作用,请尝试groupBy

Invite::whereIn('product_id', $get_products_id)
    ->where('user_id', Auth::user()->id)
    ->groupBy('product_id')
    ->get()
    ->count();

There is no need to use implode. 无需使用内爆。 you can use whereIn instead of where. 您可以使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM