我正在用Laravel开发一个社交媒体项目。我需要为跟随者和追随者提供一个定制的API。因此,我希望在用户表和跟随表之间建立一种关系。我看了很多资源,却弄糊涂了。有人能帮我处理人际关系吗?
模型
用户: id,用户名,电子邮件,密码
: id,user_id,follow_id(user_id)
追随者: id,user_id,follower_id(user_id)
API Url: http://localhost/api/follows/user_id/1
FollowController
public function user_follow($user_id)
{
$user_find = Follows::where("user_id", "=", $user_id)->get();
return response()->json($user_find, 201);
}输出
[
{
"id": 4,
"user_id": 1,
"follow_id": 4,
"created_at": "2020-03-23T15:11:48.000000Z",
"updated_at": "2020-12-11T11:10:10.000000Z"
},
{
"id": 5,
"user_id": 1,
"follow_id": 1,
"created_at": "2012-08-30T20:16:51.000000Z",
"updated_at": "2020-12-11T11:10:10.000000Z"
}
]根据用户要求带来相关的跟随者的API。但是在这里,我想给出更多的相关用户的用户信息,我该如何做呢?
发布于 2020-12-16 18:24:16
对我来说,最正确的实现如下:
首先,您不需要两个单独的表来跟踪跟踪操作。只有一张桌子你可以两者兼得。
users
*id
*username
*email
*password
user_followers
*id
*user_id
*follower_id然后,在模型中,您可以这样做:
public function followers()
{
return UserFollower::where('user_id', $this->id)->get();
}
public function following()
{
return UserFollower::where('follower_id', $this->id)->get();
}
public function followUser($userId)
{
// create & insert new row as a follower to the other user
$follower = new UserFollower();
$follower->user_id = $userId;
$follower->follower_id = $this->id;
$follower->save();
}在API中,您可以这样做:
domain/api/users/{user_id}/followers/
domain/api/users/{user_id}/following/·要从相关模型中获得更多信息,我认为你可以做一个“左撇子”。
类似这样的东西
public function followers()
{
return DB::table('user_followers')
->select('user_followers.*', 'users.email', 'users.name')
->where('user_followers.user_id', '=', $this->id)
->leftJoin('users', 'user_followers.follower_id', '=', 'users.id')
->get();
}编辑:追随者方法的另一种方法是使用基本模型类的'hasManyThrough‘方法。
public function followers()
{
return $this->hasManyThrough(UserFollower::class, User::class);
}这样,此方法将返回用户模型。
发布于 2020-12-16 17:58:59
从您的模型中可以看出,在user中为定义一个一对多的关系遵循模型如下:
跟随
public function user(){
return $this->belongsTo('App\Models\User');
}然后,从控制器中的以下内容获取相关用户:
$user_find = Follows::where("user_id", "=", $user_id)->get();
$related_user = $user_find->pluck('user');https://stackoverflow.com/questions/65327577
复制相似问题