我目前正在这样做,因为标题是这样的:
$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'])
;
在帖子值中,我需要拥有所有帖子和关系数据,例如评论和与评论相关的用户。
所以基本上在用户模型中:
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');
}
谢谢
答案 0 :(得分:1)
说实话,您可能过于复杂了。
$user = User::where('username', request('username'))->first();
$user->load(['posts.comments']);
return response()->json($user);
这可能是简化版本,但仍应表明您可以在模型上加载关系。
答案 1 :(得分:0)
我认为这会有所帮助
$q = User::with(['posts' => function ($query) {
$query->with('comments');
}])->get();
如果您要特定用户
$q = User::where('username', request('username')->with(['posts' => function ($query) {
$query->with('comments');
}])->get();