如何在Eloquent中实现这种关系?

时间:2018-06-04 06:42:01

标签: eloquent

我有SQL这个查询:

    SELECT f.follower_id, u.fname, u.lname
    FROM followers f
    INNER JOIN users u ON f.follower_id = u.id
    WHERE f.user_id = $user_id
    AND u.status = 1
    ORDER BY fname, lname
    LIMIT 10

我有两个模型:用户和关注者。

用户可以拥有许多关注者,每个关注者都有自己的用户数据。我希望能够通过这样的方式获得所有用户的关注者(状态为1):

$followers = User::get_followers();

1 个答案:

答案 0 :(得分:0)

将此添加到您的User型号:

public function followers()
{
    return $this->belongsToMany(User::class, 'followers', 'user_id', 'follower_id')
        ->where('status', 1)
        ->orderBy('fname')
        ->orderBy('lname');
}

然后您可以像这样访问它们:

$followers = $user->followers;
相关问题