I have an array with the ID of the services, and there is an array with the Product. They are related to each other as Many To Many. For expamle: Product
[1, 2, 3]
Service
[2, 3, 6]
Table
product_id | service_id |
---|---|
1 | 2 |
2 | 3 |
3 | 8 |
How can I check whether a product belongs to a service?
CodePudding user response:
You've tagged it as Laravel, and mentioned "Many to Many", which case, presumably, there are Eloquent relationships in place.
That being the case, then if a Service has one or more Products, you can check if a specific Service has a specific Product using :
$service = Service::find(2);
$product = Product::find(8);
if($service->products->contains($product)) {
echo "Service has that product";
} else {
echo "Service does not have that product";
}
CodePudding user response:
If you don't want to use Eloquent, you can use query builder
$exists = DB::table('service_product')
->whereServiceId($service_id)
->whereProductId($product_id)
->count() > 0;