mysql 同一个表 多个外键,同一张表中的多个外键

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值