POV
POV

Reputation: 12015

How to retrieve data through model?

I have Order model with another relation OrderPhoto:

public function OrderPhoto()
{
  return $this->hasMany('App\OrderPhoto');
}

In turn OrderPhoto model has relation:

public function Photo()
{
  return $this->belongsToMany('App\Photo');
}

So, how to get data from OrderModel with related data from third model Photo?

I guess this:

Order::with("OrderPhoto.Photo")->get();

to retrieve only data from Photo model for each Order

So, each Order has some OrderPhotos. Relationship is one to many.

But one item from OrderPhotos is related with primary key from table Photos. It is one to one relation.

My result query should be:

select `photos`.*, `ordersphoto`.`Orders_Id` from `photos` inner join `ordersphoto` on `ordersphoto`.`Photos_Id` = `photos`.`Id` where `ordersphoto`.`Orders_Id` in (1);

How to use hasManyThrough for this query?

Upvotes: 2

Views: 57

Answers (1)

Josh Young
Josh Young

Reputation: 1366

Just having a quick look at your relationships it looks like you could create a hasManyThrough relationship on the order Model.

public function Photo {
    return $this->hasManyThrough('App\OrderPhoto', 'App\Photo')
}

You may need to add the table keys to make it work

This will allow you to do:

Order::with("Photo")->get();

You can see more details here https://laravel.com/docs/5.5/eloquent-relationships#has-many-through

Update

Try this

public function Photo {
    return $this->hasManyThrough('App\Photo', 'App\OrderPhoto', 'Order_id', 'Photos_id', 'id', 'id')
}

It is a little hard to get my head around your DB structure with this info but you should hopefully be able to work it out. This may also help

https://laravel.com/api/5.7/Illuminate/Database/Eloquent/Concerns/HasRelationships.html#method_hasManyThrough

Upvotes: 1

Related Questions