How to get data from three models that are related to each other in Laravel 5.8

So I have this model Order which has one to many relation with ProductOrder model. And also Product model which has the same one to many relation with ProductOrder model. I can get the PorductOrder data with Product or with Order. Like this:

Order::with('product_orders')->get();

Now this is returning my orders with the associated ProductOrder data. How can I include the Products of each ProductOrder data in this collection?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Make changes of function name, field name, model name as per you requirements

Step 1:

In you ProductOrder Model use this function:

public function products()
{
    return $this->hasOne('AppProduct',  'id', 'product_id');
}

Step 2:

After this in you query you can use as:

Order::with('product_orders.products')->get();

Method 2

It sounds like ProductOrder is just a joining table/model, is that right? If that is the case, you should change to a ManyToMany relationship to of the Products model to

public function orders()
{
  return $this->belongsToMany('AppOrders', 'product_order');
}

and the Orders to
public function products()
{
  return $this->belongsToMany('AppProducts', 'product_order');
}

Then you can access like

Order::find(1)->products()->get();


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x