【问题标题】:Laravel API JSON customization and table relationshipLaravel API JSON 自定义和表关系
【发布时间】:2021-03-27 08:50:51
【问题描述】:

我正在使用 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

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

【问题讨论】:

  • 请提供有关输出的信息。你想得到什么?告诉我们您的控制器。
  • 我想从输出中有额外follow_id的用户的用户表中获取信息。
  • 使用 larave 资源和集合进行 api 响应,否则你需要从表和关系中创建一个数组,这是一个痛苦的过程 laravel.com/docs/8.x/eloquent-resources

标签: laravel relationship laravel-7 laravel-8 laravel-relations


【解决方案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();
}

编辑:followers 方法的另一种方法是使用基础模型类的“hasManyThrough”方法。

public function followers()
{
    return $this->hasManyThrough(UserFollower::class, User::class);
}

这样这个方法返回用户模型

【讨论】:

    【解决方案2】:

    从您的模型中可以看出,在 Follow 模型中为 user 定义一对多关系,如下所示:

    关注

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

    然后,从控制器中的 Follow 获取相关用户:

    $user_find = Follows::where("user_id", "=", $user_id)->get();
    $related_user = $user_find->pluck('user');
    

    【讨论】:

      猜你喜欢
      • 2021-11-09
      • 2017-01-05
      • 1970-01-01
      • 1970-01-01
      • 2018-10-16
      • 2019-01-29
      • 2021-12-12
      • 2023-04-01
      • 1970-01-01
      相关资源
      最近更新 更多