I'm trying to create a user profile which has a few friend management buttons but you only want to see what is relevant to you and the profile.
I have two tables:
user_friendships - user_id | friend_user_id
user_friendship_requests - user_id | target_user_id
The relationship to get all friendships and friendship requests would be as follows:
class User extends Model
{
public function friends()
{
return $this->belongsToMany('User', 'user_friendships', 'user_id', 'friend_user_id');
}
public function friendrequests()
{
return $this->belongsToMany('User', 'user_friendship_requests', 'user_id', 'target_user_id');
}
}
This works fine but how would I detect if the user's profile I am visiting ( $profile = User::find(1234)
) is my friend OR they have friend requested me OR I have friend requested them?
It's the case of checking if rows exist between the two users, and seeing what column contains what. I'm not sure the best way to go about this because 3 queries, one for each state, probably isn't the best performance wise.
How would I go about this?
You can add a column called 'relation' that contains an enum.
$table->enum('relation', ['request', 'friend']);
However, you still need to worry about the opposite way. For example, a friendship would be defined as :
user_id | friend_user_id | relation
1 | 2 | friend
2 | 1 | friend
or with just with one unique row but you will need to include more checks into your SQL query. I'm wondering which of the two methods is the most suitable.
let's say your id is 50 and the profile id you are visiting is 1234 it is clear that
$profile = User::find(1234)->friends()->get()
will retrieve the user and all his friends
but what about filtering this friends
$users = User::with(['friends' => function ($query) {
$query->where('friend_user_id', '=', '50');
}])->first();
if($user)return "he is a friend";
the same in the request
to get out of the box soultions read eloquent-relationships eager-loading
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.