Home > Back-end >  how to count or get record of rows, whose primary_key is not in foreign table?
how to count or get record of rows, whose primary_key is not in foreign table?

Time:08-02

I have a database that have two tables 'products' and "specifications". I want to count whose specifications are not in "specifications" table and products have duplicate names.

I have tried: Product::withCount(['specifications'])->has('specifications', '<', '1')->get(); but this is not working, taking too much time also tried with paginate but get no result.

Update: Also please let me know the RAW query for this.

CodePudding user response:

Do you mean

$productCount = Product::whereDoesntHave('specifications')->count();

$products = Product::whereDoesntHave('specifications')->get();

CodePudding user response:

Since the specification count is always going to be 0, you could hardcode the value in the query. Also, instead of has(), try doesntHave()

Product::query()
    ->select('*', DB::raw('0 as specifications_count'))
    ->doesntHave('specifications')
    ->get();
  • Related