Reputation: 103
Tables:
users
id
follows
id
user_id
follow_id
posts
id
user_id
I want to get user followed user's post.
How do I set the relationship and get
user->follow->post
?
Upvotes: 0
Views: 915
Reputation: 396
Assuming that a user can have more than one follower, and a user can follow more than one user. You need an Many To Many Relationship with the same model.
Here is:
<?php
class User extends Eloquent {
...
public function followers()
{
return $this->belongsToMany('User', 'follows', 'user_id', 'follow_id');
}
public function follows()
{
return $this->belongsToMany('User', 'follows', 'follow_id', 'user_id');
}
}
Below is how you can view the users
$user = User::find(1);
echo $user->follows()->first()->name;
echo $user->followers()->first()->name;
// or
foreach ($user->followers as $follower)
echo $follower->name . '<br>';
and etc
Upvotes: 1