【问题标题】:Returning laravel realtionship within json在json中返回laravel realtionship
【发布时间】:2018-12-11 00:34:00
【问题描述】:

我目前正在这样做,因为标题是这样的:

$user = User::where('username', request('username'))->first();

$posts = [];
$comments = [];
foreach($user->posts as $post){
 foreach($post->comments as $comment){
  array_push($comments, [
    'id' => $comment->id,
    'body' => $comment->body,
    'user' => $comment->user->only(['name', 'id']),
  ]);
 }
  array_push($posts, [
    'title' => $post->title,
    'id' => $post->id,
    'body' => $post->body,
    'comments' => $comments,
  ]);
}
return response()->json([
  'user' => $user->only(['name', 'avatar', 'age']),
  'posts' => $posts,
]);

有没有更短的方法:

$user->only(['name', 'avatar', 'age'])->withPostsOnly(['id', 'title', 'body'])->withCommentsOnly(['id', 'body']);

我知道有一种方法可以在模型中创建返回这些数据部分的方法,然后像上面一样使用它,但更短。

但是有什么方法可以使用getNameAttribute($value) 之类的东西来处理关系,所以我可以说:

$user->only(['id', 'name', 'age', 'posts']);

在帖子值中,我需要拥有所有帖子和关系数据,例如 cmets 和连接到 cmets 的用户。

所以基本上在用户模型中:

public function posts() {
  return $this->hasMany('App/Post')->only('id', 'title', 'body', 'comments');
}

在 Post 模型内部:

public function comments() {
  return $this->hasMany('App/Comment')->only('id', 'body', 'user');
}

在评论模型内部:

public function comments() {
  return $this->belongsTo('App/User')->only('id', 'name');
}

谢谢

【问题讨论】:

  • 最好使用 firstOrFail 或检查是否返回用户以避免无效用户名的致命错误。
  • 好的,谢谢

标签: laravel laravel-5 laravel-5.7


【解决方案1】:

说实话,你可能过于复杂了。

$user = User::where('username', request('username'))->first();
$user->load(['posts.comments']);
return response()->json($user);

这可能是一个简化版本,但仍应表明您可以仅在模型上加载关系。

【讨论】:

  • 在这里给我一些解释:$user->load(['posts', 'comments']); 是与用户或帖子相关的 cmets
  • 我的错,将编辑您如何加载关系的关系
  • 为什么不User::with(["posts.comments"])->where(...)->first();?将其拆分为 2 个数据库调用而不是一个的逻辑是什么?
  • 所以$user->load(['posts.comments']); 为每个帖子返回帖子和 cmets?那么posts.comments.user 应该返回带有与评论相关的用户的 cmets 帖子?
  • 效率更高一点。对于单个记录,这不是什么大问题,但是在循环中说,这会破坏您的数据库连接:P
猜你喜欢
  • 2014-10-26
  • 2016-09-04
  • 1970-01-01
  • 2016-07-13
  • 2017-03-25
  • 2017-05-24
  • 2019-06-30
  • 2018-05-31
  • 2017-11-23
相关资源
最近更新 更多