John Davidson

php - Get all the items NOT included in a giving order using Eloquent

0 comments
Message:


I have the following tables:


orders:
- id
- date

item_order:
- order_id
- item_id

items:
- id
- desc
- price

Using Eloquent, how can I get all the items NOT included in a giving order (say, the order with id = 6)?


I'm trying to do relationships & subqueries, but without luck.


Thanks in advance.



My Answer:
You can achieve this by defining a relationship between the `orders` and `items` tables and then using Eloquent to query for all items that are not included in a specific order.

First, define the relationships in your models:

Order.php:
php
class Order extends Model
{
public function items()
{
return $this->belongsToMany(Item::class, 'item_order', 'order_id', 'item_id');
}
}


Item.php:
php
class Item extends Model
{
public function orders()
{
return $this->belongsToMany(Order::class, 'item_order', 'item_id', 'order_id');
}
}


Then, you can use Eloquent to query for all items that are not included in a specific order (e.g., order with id = 6):

php
$itemsNotInOrder = Item::whereDoesntHave('orders', function ($query) {
$query->where('order_id', 6);
})->get();


This query will return all items that are not included in the order with id = 6.

Rate this post

3 of 5 based on 9135 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us