复合外键 Laravel

Jac*_*rry 0 key composite laravel

我发现很难创建复合外键。我想要一个同时具有 'movieid' 和 'cinemaid' 作为复合外键的会话表。这是因为一个会话需要电影和电影院的位置。

我目前的架构如下:

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

$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');
Run Code Online (Sandbox Code Playgroud)

});

我找不到关于如何在 laravel 中创建复合外键的很多信息。我发现的最好的事情:

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

然而,在这个例子中,他们从一个表中提取两个外键,在我上面的例子中,你可以看到我需要从“电影”表和“电影”表中获取数据。我想也许使用 on(array('movies', 'cinema') 会起作用,但它出现了“数组到字符串转换”的错误。

我试过删除 (array()) 部分,但它也不能那样工作。

如果我不打算使用复合外键,我也很乐意听到任何替代解决方案。

谢谢一堆,

杰克。

Bre*_*ite 5

外键连接到一个其他的表。所以你需要两个独立的外键,一个 formovies一个 for cinema

$table->foreign('movieId')->references('id')->on('movies');
$table->foreign('cinemaId')->references('id')->on('cinema');
Run Code Online (Sandbox Code Playgroud)

另外,我猜您想在session表中的两个字段movieIdcinemaId. 如果是这样,您需要决定是否将新的复合索引作为索引session

如果您希望复合索引成为您的主索引,那么您也不需要该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');

});
Run Code Online (Sandbox Code Playgroud)

或者,如果您希望将 保留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');

});
Run Code Online (Sandbox Code Playgroud)

这有帮助吗?