Multiple Foreign Key from the same table

旧巷老猫 提交于 2020-04-18 05:45:39

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/61162746/multiple-foreign-key-from-the-same-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!