Laravel雄辩:如何选择朋友用户模型? [英] Laravel Eloquent: How to select friend user model?

查看:149
本文介绍了Laravel雄辩:如何选择朋友用户模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试选择朋友的所有用户对象。朋友可以是保存的友谊的第一用户或第二用户。

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?

这里是我尝试过的:

$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();"

$ b b

有任何想法吗?

Any ideas?

编辑

找到了使用 orOn 的选项。但是,我仍然需要确保所选用户不是您。

I found the option to use orOn. However, I still need to make sure the selected user isn't you.

数据库结构

users
-----
id (int)
name (varchar)

friends
-----
id (int)
user_1 (int)
user_2 (int)
accepted (int)


推荐答案

应查询您用户,而不是您的朋友模型,因为您想要接收 User 对象。接下来,您可以添加另一个where子句,以便不会得到user_id与变量匹配的行。

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.

因此结果将是这样:

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();

这篇关于Laravel雄辩:如何选择朋友用户模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆