gpt4 book ai didi

php - 外键如何引用多个主键

转载 作者:行者123 更新时间:2023-11-29 17:12:57 25 4
gpt4 key购买 nike

enter image description here

我正在 Laravel 中开发一个系统,用户可以在其中发帖、回答并对帖子或答案进行投票。

一种方法是为此制作单独的投票表,但我想用一张表作为投票来做到这一点。

我希望投票表中的 content_id 应该引用两个主键: posts.id 和 post-answers.id

如果该解决方案不可行,则建议替代解决方案。提前致谢。

我尝试进行此迁移,但没有成功,表已成功创建,但外键仅指向一个主键。

public function up()
{
Schema::create('contentvotes',function(Blueprint $table){
$table->increments('id');
$table->enum('content_type',['post','post_answer']);
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->integer('content_id')->unsigned();
$table->foreign('content_id')->references('id')->on('posts');
$table->foreign('content_id')->references('id')->on('postanswers');
$table->boolean('status');
$table->timestamps();
});
}

最佳答案

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

public class Model {
...
...

protected $appends = ['post', 'post_answer']

public class getPostAttribute()
{
return Post::find($this->attribute('content_id'))
}

public class getPostAnswerAttribute()
{
return PostAnswer::find($this->attribute('content_id'))
}


}

关于php - 外键如何引用多个主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51799400/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com