[英]How to update a column as Foreign key on Laravel?
我正在尝试将表列更新为引用另一个表列的外键。
例如,我有名为帐户和货币的表。 以下是账户列:id、label、currency 和 Currencies 列:id、label
我已经像这样在他们两个上创建了迁移:
public function up()
{
Schema::create('accounts', function (Blueprint $table) {
$table->id();
$table->string('label', 255);
$table->integer('currency');
});
}
这是货币:
public function up()
{
Schema::create('currencies', function (Blueprint $table) {
$table->id();
$table->string('label', 255);
});
}
我想将account
的currency
列分配给currency
的id
。
我试过这个:
public function up()
{
Schema::table('accounts', function (Blueprint $table) {
$table->foreign('currency')
->references('id')
->on('currencies')
->onUpdate('cascade');
});
}
但它抛出这个错误:
SQLSTATE[HY000]: General error: 1005 Can't create table `test`.`accounts` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `accounts` add constraint `accounts_currency_foreign` foreign key (`currency`) references `currencies` (`id`) on update cascade)
我该如何编写迁移?
货币中的 id 列来自类型: unsignedBigInteger
您必须首先将货币更新为这种类型才能成为外键。
public function up()
{
Schema::table('accounts', function (Blueprint $table) {
$table->unsignedBigInteger('currency')->change();
$table->foreign('currency')
->references('id')
->on('currencies')
->onUpdate('cascade');
});
}
或者如果可能,您可以修改第一次迁移。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.