I have a Laravel application with a MySQL database that has 3 tables: Publication, Comment and User.
When I display a publication to user I call WS GET Publication By Id and WP GET Comment By Publication Id to display all comments related to that publication.
I want to know if there's a way to avoid Calling WP GET User By Comment Id for each Comment, because when I display a comment I also need to display some information for user who commented.
Can I add multiple user Foreign Keys in table Comment and use them?
Thanks in advance.
解决方案
This is a very generic usecase. Can you see if this answers your question.
Publication model{
whatever fields you have,
//Comments --> One to many relation with Comment model
public function comments()
{
return $this->hasMany('App\Comment');
}
}
Comment Model{
whatever fields you have,
//User --> One to one relation with User model
public function user()
{
return $this->hasOne('App\User');
}
}
User Model{
fields...
}
In your controller, you can get the publications with comments and users by using with function.
$pub = Publication::first()->with('comments.user');
I hope this helps.