remedy.
remedy.

Reputation: 2022

How to create a relationship across three models in laravel-4?

I have the following data structure:

 Table t:
      (PK)id
          order_id (this links to table or's id)


 Table is:
      (PK)id
          tracking_id (this links to table or's tracking_id)

 Table or:
      (PK)id    (this links to table t's order_id)
      (FK)tracking_id

Now inside my model (T.php)

I set the following relationship:

 public function iS()
 {
    return $this->hasMany('is', 'tracking_id', 'order_id');
 }

Now obviously this doesn't work because tracking_id is not a match to order_id.

How do I link these three tables together so that I can retrieve the is data that corresponds to the t table?

I'm calling it this inside my Controller:

  $o = O::with('t', 't.iS')->where('id','=',$id)->first(); (O is my model for "o" table)

Upvotes: 0

Views: 34

Answers (1)

Nein
Nein

Reputation: 419

You are looking for hasManyThrough relationship. http://laravel.com/docs/eloquent#has-many-through

In the documentation example: Country has Users and Users have Posts. To get posts of each country you define:

class Country extends Eloquent {

    public function posts()
    {
        return $this->hasManyThrough('Post', 'User', 'country_id', 'user_id');
    }

}

In your example: T has Or and Or has Is

Upvotes: 1

Related Questions