DazChong
DazChong

Reputation: 3562

Laravel 4 Eloquent ORM advance relationships

Greeting all artisans.

I am finding the best practice to solve the relationships as tables below:

TABLE "companies"

id     name

1      Apple
2      Google
3      Facebook
...

TABLE "staffs"

id     name   company_id

1      Alex   1
2      Benny  1
3      Tony   2
...

TABLE "posts"

id     content           staff_id

1      Lorem ipsum A     1
2      Lorem ipsum B     1
3      Lorem ipsum C     5
...

How can I define relationships with eloquent so that I can select all 'posts' from specific 'company'. I can declare additional 'company_id' column in 'posts' table for workaround.

But can we using eloquent to select as like example:

$posts = Post::where('staff_id', IN, COMPANY_ID)->get();

Thanks in advance

Upvotes: 1

Views: 3652

Answers (2)

DazChong
DazChong

Reputation: 3562

Finally Laravel 4.1 provide this feature called hasManyThrough! Horray!

http://laravel.com/docs/eloquent#has-many-through

Upvotes: 6

Alexander Cogneau
Alexander Cogneau

Reputation: 1274

EDIT: I seem to have misunderstood the question, you can eager load nested relationships like this:

$company = Company::find(COMPANY_ID)->with('staff.posts')->get();

then you can loop through them:

foreach($company->staff() as $staff)
{
     foreach($staff->posts() as $post)
     {
         echo $post->content;
     }
}

Both relationships need to be defined though.

// models/company.php
public function staff()
{
   return $this->hasMany('Staff');
}

and

// models/staff.php
public function posts()
{
   return $this->hasMany('Post');
}

Upvotes: 3

Related Questions