Models:
- Order
- OrderItem
- Product
- Category
Relationships:
- Order **hasMany** OrderItem (order_items)
- OrderItem **belongsTo** Product (product)
- Product **hasMany** Category (categories)
- Category **belongsToMany** Category (exchangables) via pivot table 'exchangables'
Pivot table exchangable looks like this:
category_id (FK:category.id) | exchangable_category_id (FK:category.id)
I am trying to get Order with only OrderItem(s) that has Product(s) Category(ies) as exchangables (pivot).
Essentially I want only order items that can be exchanged for products from specific categories (in pivot).
yes, that exchangables table is joining on same model Category, M-2-M
I tried this:
$order = \App\Order::where('id', $orderId)
->has('order_items.product.categories.exchangables')
->first();
And I tried this:
$order = \App\Order::where('id', $orderId)
->with(['order_items.product.categories' => function($query)
{
$query->has('exchangables');
}]
)
->first();
And I even tried this:
$order = \App\Order::where('id', $orderId)
->with(['order_items' => function($query) {
$query->with(['product', function($query2) {
$query2->with(['categories', function($query3) {
$query3->with('exchangables')->has('exchangables');
}]);
}]);
->first();
No luck. It returns everything without regard that some order_items' product categories DO NOT have exchangables.
If question is unclear, I can try explaining it better. My models relationship is properly configured. I've written thousand lines ofcode using combination of all those relationshps, but never nested that deep. I don't want to post pages of model code and consume a lot of space.
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire