[英]Laravel Eloquent: How to select friend user model?
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?
我该如何使用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
. 我找到了使用
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. 您应该查询您的
User
而不是您的Friend
模型,因为您想接收User
对象的列表。 Next, you can just add another where clause to not get lines where the user_id matches the variable. 接下来,您可以仅添加另一个where子句,以不获取user_id与变量匹配的行。
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.