Reputation: 21
I'm creating feature for order in canteen project. I have made these eloquent relationship:
If I want to get canteen data of the order_product, I can just type order_product->product->canteen->id.
This is what I have done to show details of orders. But the lists aren't ordered by the canteen id. So, I want that the eloquent relationship of order->products return products of orders that ordered by canteen_id. Do anyone have solution for this?
Upvotes: 1
Views: 172
Reputation: 422
I don't think you can achieve it using your current method (or using Eloquent method), because the parent of the object is OrderProduct
and each of the Canteen
is inside the OrderProduct
, so if you apply an order by using Eloquent, it will order it only for each of the OrderProduct
, not globally. For illustration:
{
order_products: [
{
id: 1,
canteen: {
id:1
}
},
{
id: 2,
canteen: {
id:3
}
},
{
id: 3,
canteen: {
id:2
}
}
]
If you apply the order by from the format above, it will stay the same because: (1) you only have 1 Canteen
object, and (2) if you have a one to many relationship to Canteen
, it will only sort the Canteen
's id separately. So, the format that you're looking for might be similar to this:
[
{
canteen_id: 1,
order_product_id: 2
},
{
canteen_id: 2,
order_product_id: 3
},
{
canteen_id: 3,
order_product_id: 1
}
]
That way, you can sort Canteen
's id globally throughout the entire list. There are 2 ways to achieve this. The first one is taking the data from the Canteen
model, then work your way through OrderProduct
. Or, you can do it raw query-style, so you can create your own object (which has no more grouping like the Eloquent provides) and order it by Canteen
's id.
Upvotes: 1