I am trying to select all user objects of friends. A friend can either be the first user or the second user of the saved friendship. How do I do this using Eloquent?
Here is what I've tried:
$friends = Friend::select(array('users.id', 'users.name'))
->leftJoin('users', function($join)
{
$join->on('user_id_1', '=', 'users.id');
// $join->on('user_id_2', '=', 'users.id');
})
->where( ['user_id_1' => $myID, 'accepted' => '1'] )
->orWhere( ['user_id_2' => $myID, 'accepted' => '1'] )->get();"
Any ideas?
Edit
I found the option to use orOn
. However, I still need to make sure the selected user isn't you.
Database structure
users
-----
id (int)
name (varchar)
friends
-----
id (int)
user_1 (int)
user_2 (int)
accepted (int)
You should query on you User
and not on your Friend
model because you want to receive a list of User
objects. Next, you can just add another where clause to not get lines where the user_id matches the variable.
So the result would be something like this:
User::leftJoin('friends', function ($join) {
$join->on('friends.user_id_1', '=', 'users.id')
->orOn('friends.user_id_2', '=', 'users.id');
})
->where(function ($query) use ($myID) {
// Group orwhere functions so the query builder knows these belong together
$query->where([
'friends.user_id_1' => $myID,
'friends.accepted' => true
])
->orWhere([
'friends.user_id_2' => $myID,
'friends.accepted' => true
]);
})
->where('users.id', '!=', $myID) // Exclude the user with id $myID
->get();
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.