0

我正在使用 Laravel 开发一个社交媒体项目。我需要为关注者和关注者提供定制的 API。因此,我想在用户表与关注者和关注表之间建立关系。我查看了很多资源,但感到困惑。谁能帮我处理人际关系?

楷模

用户: id,用户名,电子邮件,密码

关注: id、user_id、follow_id(user_id)

追随者: id、user_id、follower_id(user_id)

API 网址: http://localhost/api/follows/user_id/1

跟随控制器

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。但是在这里,我想给相关用户的附加用户信息,我该怎么做呢?

4

2 回答 2

1

对我来说最正确的实现如下所示:

首先,您不需要两个单独的表来跟踪后续操作。一张桌子你可以同时拥有。

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/

• 要从相关模型中获取更多信息,我认为您可以执行“leftJoin”。

类似的东西

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-16T18:24:16.427 回答
1

As it is evident from your model, define a one to many relationship for user in the Follow model as below:

Follow

public function user(){
    return $this->belongsTo('App\Models\User');
}

Then, get the related user from the Follow in your controller:

$user_find = Follows::where("user_id", "=", $user_id)->get();
$related_user = $user_find->pluck('user');
于 2020-12-16T17:58:59.173 回答