【问题标题】:How to implement this relationship in Eloquent?如何在 Eloquent 中实现这种关系?
【发布时间】:2018-11-13 10:36:13
【问题描述】:

我有 SQL 这个查询:

选择 f.follower_id、u.fname、u.lname FROM 追随者 f INNER JOIN users u ON f.follower_id = u.id 其中 f.user_id = $user_id AND u.status = 1 按 fname、lname 排序 限制 10

我有两个模型:用户和追随者。

一个用户可以有很多粉丝,每个粉丝都有自己的用户数据。我希望能够通过执行以下操作来获取用户的所有关注者(状态为 1):

$followers = User::get_followers();

【问题讨论】:

标签: eloquent


【解决方案1】:

将此添加到您的 User 模型中:

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

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

$followers = $user->followers;

【讨论】:

  • 在我的用户模型中,我粘贴了您的代码。在我的控制器中,我添加了以下代码:$followers = $user->followers;。我打印了 $followers 并没有得到预期的结果。
  • 是的,$followers 是空的。
  • 发布dd($user->followers()->toSql());的结果。
  • 我什至尝试将功能缩减为:return $this->belongsToMany(User::class, 'followers', 'user_id', 'follower_id');
  • select * from users inner join followers on users.id = followers.follower_id 其中followers.user_id 为空
猜你喜欢
  • 2018-04-17
  • 2020-06-28
  • 2014-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-11
  • 2023-03-04
  • 1970-01-01
相关资源
最近更新 更多