2016-09-28 115 views
0

我發現很難創建一個複合外鍵。我想要一個將'movieid'和'cinemaid'作爲複合外鍵的會話表。這是因爲一個會話需要電影和電影放映。複合外鍵Laravel

我目前的架構是folllowing:

模式::創建( '會話',函數(藍圖$表){

$table->increments('id'); 
$table->integer('movieId'); 
$table->integer('cinemaId'); 
$table->foreign(array('movieId', 'cinemaId'))->references(array('id', 'id'))->on(array('movies', 'cinema')); 
$table->dateTime('time'); 

});

我無法找到關於如何在laravel中創建複合外鍵的許多信息。我找到的最好的事情:

http://www.geexie.com/composite-primary-foreign-keys-laravel/

然而,在這個例子中,他們拉從一個表,兩個外鍵,其中,在我上面的例子中,你可以看到,我需要從兩個數據「電影」表和「電影院」表。我想也許使用on(陣列('電影','電影')將工作,但它出現了錯誤「陣列到字符串轉換」

我試着刪除(數組()但它不工作,這樣無論是。

我也很樂意聽到任何其他解決辦法,如果我不是假設使用複合外鍵。

多謝,

Jack。

回答

0

一個外鍵鏈接到一個其他表。所以你需要兩個獨立的外鍵,一個用於movies,另一個用於cinema

$table->foreign('movieId')->references('id')->on('movies'); 
$table->foreign('cinemaId')->references('id')->on('cinema'); 

而且,我猜你想在session表一個綜合指數,上兩個字段movieIdcinemaId。如果是這樣,您需要決定是否將新複合索引作爲上的主要索引。

如果您希望組合索引是您的主索引,那麼您不需要id字段,因此您需要刪除$table->increments('id')行。你最終會是這樣的:

Schema::create('session', function (Blueprint $table) { 

$table->integer('movieId'); 
$table->integer('cinemaId'); 
$table->primary(['movieId', 'cinemaId']); // note, this is a *primary* key 
$table->foreign('movieId')->references('id')->on('movies'); 
$table->foreign('cinemaId')->references('id')->on('cinema'); 
$table->dateTime('time'); 

}); 

或者,如果你想保持id作爲主要指標,然後你只想綜合指數是一個普通的舊索引。所以你可能會這樣做:

Schema::create('session', function (Blueprint $table) { 

$table->increments('id'); 
$table->integer('movieId'); 
$table->integer('cinemaId'); 
$table->index(['movieId', 'cinemaId']); // This is an index, but *not* a primary key 
$table->foreign('movieId')->references('id')->on('movies'); 
$table->foreign('cinemaId')->references('id')->on('cinema'); 
$table->dateTime('time'); 

}); 

這有幫助嗎?

+0

謝謝布倫丹,但這是從7個月前:) –