同一张表中的多个外键 [英] Multiple Foreign Key from the same table

查看:831
本文介绍了同一张表中的多个外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有MySQL数据库的Laravel应用程序,该数据库具有3个表:PublicationCommentUser.

I have a Laravel application with a MySQL database that has 3 tables: Publication, Comment and User.

当我向用户显示发布时,我调用WS GET Publication By IdWP GET Comment By Publication Id来显示与该发布相关的所有注释.

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.

我想知道是否有一种方法可以避免为每个评论调用WP GET User By Comment Id,因为当我显示评论时,我还需要为评论的用户显示一些信息.

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.

我可以在表Comment中添加多个用户外键并使用它们吗?

Can I add multiple user Foreign Keys in table Comment and use them?

谢谢.

推荐答案

这是一个非常通用的用例.你能看看这是否回答了你的问题.

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...
}

在控制器中,可以通过with函数使用带有注释和用户的出版物.

In your controller, you can get the publications with comments and users by using with function.

$pub = Publication::first()->with('comments.user');

我希望这会有所帮助.

这篇关于同一张表中的多个外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆