简体   繁体   中英

Counting Existing ID's in a different table - laravel

I have two items in a table called products with id's 1 and 2 . There is a table called invite which has foreign key product_id for products .

In my controller below, i am trying to count the number of product id's that is existing in the invite table.

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. meaning the total count is 2 (although product id 2 appears twice.

When i run my code below, i get a count of 1 instead of 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 . 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 :

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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