[Vuejs]-How to not get some data based on records in another table with laravel eloquent?

0👍

Presuming you have the id for the Request you wanted to filter out, the SQL query will be roughly looked like

SELECT * FROM `products` WHERE NOT EXISTS 
         (SELECT * FROM `request_items` where `products`.`id` = `product_id` and `request_id` = ? )

I had to make additional assumtion as you didnt provide the model, i’d just assume the following

class Product extends Model
{
     public function requestItems()
     {
       return $this->hasMany(RequestItems::class);
     }
}

class RequestItems extends Model
{
     public function products()
     {
       return $this->belongsTo(Product::class);
     }
}

Then we can use doesntHave query criteria to find products that dont have relationship with
the RequestItems for given request id (in this example its 1).

Products::doesntHave('requestItems', 'and',
                     function($query){ $query->where('request_id', '=', 1); }
                    );

Hope it helps. I havent tried it myself, but i believe it would works. You can use toSql
method to see its resulting SQL query.

Note: some insight on the differece of IN and EXISTS

Leave a comment