【发布时间】:2017-07-12 10:01:35
【问题描述】:
我有以下表格
USERS = username | email | name
FOLLOWERS = user_id | follower_id
当登录用户点击“关注”时,我的代码将他的 id 保存在 followers.follower_id 中,而他想要关注的用户的 id 保存在 followers.user_id 中。
要查看用户拥有多少关注者以及用户关注了多少用户,我使用:
$followers = Follower::where('user_id', $user->id)->count();
$following = Follower::where('follower_id', $user->id)->count();
这很好用,但我想显示有关一位用户的关注者的信息。我尝试了以下方法:
$first_follower = $followers[0]->user->username;
但它返回的是用户关注而不是关注者。
我想知道如何获取关注者的信息
用户模型
protected $fillable = ['username','email','name'];
public function follow() {
return $this->hasMany('Shop\Follower');
}
追随者模型
protected $fillable = ['user_id','follower_id'];
public function user() {
return $this->belongsTo('Shop\User');
}
【问题讨论】:
-
你应该使用多对多关系来克服这个问题
标签: php laravel eloquent foreign-keys many-to-many