Stuck on this. I use this same query without Id to get all the successfully get all this data.
$orders = $this->order
->with('orderDetails', 'orderDetails.product')
->today()
->get();
Relationships
Order:
public function orderDetails(){
return $this->hasMany('App\OrderDetail', 'order_id');
}
OrderDetail:
public function order()
{
return $this->belongsTo('App\Order', 'order_id', 'id');
}
public function product()
{
return $this->belongsTo('App\Product', 'id_products', 'id');
}
But trying to use the same thing to get data for a particular order doesn't return the order_details.
public function invoice(Request $request, $id)
{
$ordered = $this->order
->find($id)
->with('orderDetails', 'orderDetails.product');
return response()->json($ordered);
}
Why is it behaving differently when passed an id?
When you use find
the query is executed before other directives. You need to be using where
:
$ordered = $this->order
->where('order_id', $id)
->with('orderDetails', 'orderDetails.product')
->get();
Try to use just this way:
$ordered = $this->order->find($id);
return response()->json($ordered);
The laravel already turned to relationships based on no mapping that you enter in the model. In this case, your orderDetails in your response will look like this:
Order: { Id: "1", Xpto: "whatever", OrderDetails: { Id: "1" } }