Get content from Database when relationship (pivot table) exists
Hi there,
i build a small project to post as post, follow other users and see them posts - when they are friends / follows.
I have three tables (simplified)
// posts
id
user_id
content
// users
id
username
// relations (i create two inserts a -> b, b -> a)
user_id
friend_id
is_active (the requested user must approve the request)
To get the posts from one user is no problem. But how can i get the data when these relationships are "active"? Keep in mind: The relationship must be approved. I know how i setup the database etc., but i stuck on the part when i check "these two users are friends, get the data".
When a user have 100 friends, it must get the posts from all friend, there are active.
setup the user model to have 2 methods for their friends:
1 that returns all friends (and open requests)
and 1 that only returns the active friends that have been accepted.
When you want a user with all posts of their active friends, you use the activefriends relation.
public function friends()
{
return $this->belongsToMany(User::class, 'relations', 'friend_id');
}
public function activefriends()
{
return $this->belongsToMany(User::class, 'relations', 'friend_id')->wherePivot('is_active', true);
}