[英]Followers / Following and finding who follows Laravel
I have my Relation table which goes as following: 我的关系表如下:
UserId (PK)
FollowingId
created_at
updated_at
I am able to get who the user is following and their usernames by doing the following: 通过执行以下操作,我可以获得用户关注的用户及其用户名:
My controller: 我的控制器:
$findingWhoIFollow = User::find($userId)->relations()->FindUserName()->get();
My model (user): 我的模型(用户):
public function relations()
{
return $this->hasMany(Relation::class, 'UserId', 'id');
}
My model: (relation) 我的模型:(关系)
protected $primaryKey = 'UserId';
public function user()
{
return $this->belongsToMany(User::class, 'id', 'UserId');
}
public function scopeFindUserName($query)
{
return $query->join('User', 'User.id', '=', 'Relation.FollowingId');
}
and then i am able to get the usernames of the people I follow like this: 然后我就可以像这样获得我关注的人的用户名:
@foreach($findingWhoIFollow as $iFollow)
{{$iFollow->Username}}
@endforeach
I am however struggling to do the inverse of this eg: getting the users who follow my accounts user names. 但是,我正在努力做到与之相反的事情,例如:获得遵循我帐户的用户的用户名。 I believe it's an issue with my relationships and I am missing something obvious.
我认为这是我的人际关系问题,我缺少明显的东西。
通过根据建议的重复Fabio Antunes修正我的关系来解决此问题( 与Laravel建立的友谊系统:多对多关系 )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.