【发布时间】: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