一个外键如何引用多个主键

ecfsfe2w  于 2021-06-23  发布在  Mysql
关注(0)|答案(2)|浏览(719)


我在拉威尔的一个系统上工作,在这个系统中,用户可以发布、回答和投票。
一种方法是制作单独的投票表,但我想用一张表作为投票表。
我希望投票表中的content\u id应该引用两个主键posts.id和post-answers.id
如果该解决方案不可行,则建议另一种解决方案。提前谢谢。
我试图进行此迁移,但没有成功创建表,但外键只指向一个主键。

  1. public function up()
  2. {
  3. Schema::create('contentvotes',function(Blueprint $table){
  4. $table->increments('id');
  5. $table->enum('content_type',['post','post_answer']);
  6. $table->integer('user_id')->unsigned();
  7. $table->foreign('user_id')->references('id')->on('users');
  8. $table->integer('content_id')->unsigned();
  9. $table->foreign('content_id')->references('id')->on('posts');
  10. $table->foreign('content_id')->references('id')->on('postanswers');
  11. $table->boolean('status');
  12. $table->timestamps();
  13. });
  14. }
8fsztsew

8fsztsew1#

对我来说,我会这样做。不是最佳实践,但这是可行的方法

  1. public class Model {
  2. ...
  3. ...
  4. protected $appends = ['post', 'post_answer']
  5. public class getPostAttribute()
  6. {
  7. return Post::find($this->attribute('content_id'))
  8. }
  9. public class getPostAnswerAttribute()
  10. {
  11. return PostAnswer::find($this->attribute('content_id'))
  12. }
  13. }
展开查看全部
k2fxgqgv

k2fxgqgv2#

一个外键不能引用多个表中的主键。
例如,post a和post answer b可能具有相同的id,数据库如何知道它是哪个id。
我注意到你有一个内容类型的专栏,我相信你已经意识到这个问题。内容类型和内容id实际上是一个复合外键。同样,它可以引用一个表。
解决方案:你需要引入多态性。您可以将post和postanswer合并到一个表中并添加类型列。
为了尽量减少数据迁移的工作量,您的主键可以是id和type。否则,id是更好的主键。

相关问题