I am making an Api with Laravel, and I wanted to make a route: posts/comments where it would show all the posts with their respective comments in json format, but when showing the posts I wanted there to be a new field where the comments would be shown there , something like that:
"Posts": [
{
"id": 1,
"user_id": 7,
"titulo": "Dr.",
"contenido": "Adipisci sequi nam distinctio inventore magnam rerum fuga.",
"created_at": "2020-10-17 17:16:49",
"updated_at": "2020-10-17 17:16:49"
"Comentarios": "Aqui se muestran todos los comentarios del post"
},
{
"id": 2,
"user_id": 2,
"titulo": "Dr.",
"contenido": "Quia dicta sunt mollitia eos tenetur.",
"created_at": "2020-10-17 17:16:49",
"updated_at": "2020-10-17 17:16:49"
"Comentarios": "Aqui se muestran todos los comentarios del post"
},
My question is, how can I make it show me the posts with their respective comments like the previous example?
api.php
Route::get('posts/comments', 'PostController@posts_comments');
PostController.php
public function posts_comments(){
return response()->json([
"Posts" => DB::table('posts')->get(),
"Comments" => DB::table('comments')->get(), //solo muestra la tabla, no hay relacion con un post
],200);
}
Model Post.php
class Post extends Model
{
public function user() {
return $this->belongsTo('App\User');
}
public function comment(){
return $this->hasMany('App\Comment');
}
}
Model Comment.php
class Comment extends Model
{
public function post(){
return $this->belongsTo('App\Post');
}
}
Observations:
DB
and its methodtable
to constitute ajoin
I am telling you about the above because you are doing 2 isolated queries that will return information to you but they do not have under this criterion that you use to show the information with the structure that you want ( that is, there you only have 2
SELECTS
independent of each other ).Once the previous points have been clarified, in the comment model declare the inverse of the relationship, which would be:
belongsTo()
like this ( at some point you will end up occupying it ):Once the above is done, now we can indicate a query that returns the requested information in this way:
The above will return 2 collections:
References
I'll leave the rest to you...