[英]How a foreign key refer multiple primary keys
我正在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'))
}
}
一個外鍵不能引用多個表中的主鍵。
例如,您可能具有相同ID的Post A和Post Answer B,數據庫如何知道它的標識。
我注意到您有一個content_type列,並且我相信您已經意識到了這個問題。 您的content_type和content_id實際上是一個復合外鍵。 同樣,它可以引用一個表。
解決方案:您需要引入多態性。 您可以將發布和發布答案合並到一個表中並添加類型列。
為了最大程度地減少數據遷移的工作量,您的主鍵可以是ID和類型。 否則,ID是更好的主鍵。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.