[英]How to update a column as Foreign key on Laravel?
I'm trying to update a table column as foreign key which references on another table's column.我正在尝试将表列更新为引用另一个表列的外键。
In example, I have tables named as accounts and currencies.例如,我有名为帐户和货币的表。 Here are the accounts columns: id, label, currency And Currencies columns: id, label以下是账户列:id、label、currency 和 Currencies 列:id、label
I have created migrations on both of them like that:我已经像这样在他们两个上创建了迁移:
public function up()
{
Schema::create('accounts', function (Blueprint $table) {
$table->id();
$table->string('label', 255);
$table->integer('currency');
});
}
Here is the currencies:这是货币:
public function up()
{
Schema::create('currencies', function (Blueprint $table) {
$table->id();
$table->string('label', 255);
});
}
I want to assign account
's currency
column to currency
's id
.我想将account
的currency
列分配给currency
的id
。
I have tried this:我试过这个:
public function up()
{
Schema::table('accounts', function (Blueprint $table) {
$table->foreign('currency')
->references('id')
->on('currencies')
->onUpdate('cascade');
});
}
But it throws this error:但它抛出这个错误:
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)
How can I write the migration?我该如何编写迁移?
the id column in currency is from type: unsignedBigInteger
货币中的 id 列来自类型: unsignedBigInteger
you have to update currency to this type first to be able to be a foreign key.您必须首先将货币更新为这种类型才能成为外键。
public function up()
{
Schema::table('accounts', function (Blueprint $table) {
$table->unsignedBigInteger('currency')->change();
$table->foreign('currency')
->references('id')
->on('currencies')
->onUpdate('cascade');
});
}
or you can modify the first migration if possible.或者如果可能,您可以修改第一次迁移。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.