简体   繁体   中英

how to count or get record of rows, whose primary_key is not in foreign table?

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 1: Also please let me know the RAW query for this.

Update 2: Here is the Product Relation code:

public function specifications()
    {
        return $this->hasMany('App\Specification');
    }

Here is the function I made for deleting duplicate products and there specifications.

 public function deleteDuplicateWithCountZero() {
     
        $duplicateProducts = Product::whereIn('name', function ( $query ) {
            $query->select('name')->from('products')->groupBy('name')->havingRaw('count(*) > 1');
        })->paginate(50);
        
        
        foreach($duplicateProducts as $duplicateProduct) {
              
              $results = Product::where('name', '=', $duplicateProduct->name)->withCount(['specifications'])->get();
              
              $productCount = count($results);
              foreach($results as $result) {
                  if($result->specifications_count == 0 && $productCount > 1) {
                      $product = Product::find("$result->id");
                      Specification::where('product_id', "$product->id")->delete();
                      $product->delete();
                      $productCount--;
                  }
              }
          }
        echo "Complete"; die();
 
 }

Problem: How can I know all products and their specifications are deleted until count query, But count query taking too much time for all data. Please also suggest if I can correct this thing in phpmyadmin with a query.

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

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