Schema::table('performance', function($table)
{
$table->foreign('song_id')
->references('id')
->on('songs')
->onDelete('cascade');
});
Schema::table('performance', function($table)
{
$talbe->foreign('artist_id')
->references('id')
->on('artists')
->onDelete('cascade');
});
我收到一个错误: “在非对象上调用成员函数 foreign()” .
最佳答案
相反,您不能对外键使用多个命令。您只需要一个外键命令并组合您要定义的所有行。这是您应该运行的代码。
Schema::table('performance', function (Blueprint $table)
{
$table->unsignedInteger('song_id');
$table->unsignedInteger('artist_id');
$table->foreign(['song_id','artist_id'])->references(['id','id'])
->on(['song','artists'])->onDelete(['cascade','cascade']);
});
如果不行(之前的 Laravel 版本可能不行),我们可以用普通的 SQL 语句添加其他外键。
Schema::table('performance', function (Blueprint $table)
{
$table->unsignedInteger('song_id');
$table->unsignedInteger('artist_id');
$table->foreign('song_id')->references('id')
->on('song')->onDelete('cascade');
});
DB::statement(
"ALTER TABLE performance ADD FOREIGN KEY (artist_id) REFERENCES artists(id) ON DELETE CASCADE"
);
希望能帮助到你!
关于laravel-4 - 在 migrate laravel 中的同一张表上创建多个外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27010263/