【发布时间】:2021-09-20 21:33:27
【问题描述】:
我正在使用 Laravel 5.8 开发我的项目,我只是创建一个迁移,如下所示:
public function up()
{
Schema::create('user_wallet_transactions', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedSmallInteger('user_id');
$table->foreign('user_id')->references('usr_id')->on('users');
$table->unsignedSmallInteger('wallet_id');
$table->foreign('wallet_id')->references('id')->on('wallets');
$table->string('amount');
$table->string('description');
$table->timestamps();
});
}
但是当我运行它时,我得到了这个错误:
SQLSTATE[HY000]: General error: 1005 Can't create table `nanonew_main`.`user_wallet_transactions` (errno: 150 "Foreign key
constraint is incorrectly formed") (SQL: alter table `user_wallet_transactions` add constraint `user_wallet_transactions_user_id_foreign` foreign key (`user_id`)
references `users` (`usr_id`))
我不知道这里出了什么问题!我的表users 是这样的,字段名为usr_id:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('usr_id');
$table->string('usr_name')->unique();
$table->boolean('usr_is_admin')->default(0)->comment('0 = admin , 1 = not admin');
$table->boolean('usr_is_active')->default(0);
$table->string('usr_email')->unique()->nullable();
$table->timestamp('usr_email_verified_at')->nullable();
$table->string('usr_password');
$table->rememberToken();
$table->timestamps();
$table->engine = 'InnoDB';
});
}
而表wallets也有名为id的字段:
public function up()
{
Schema::create('wallets', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('title');
$table->string('name')->unique();
$table->tinyInteger('is_active');
$table->tinyInteger('is_cashable');
$table->timestamps();
});
}
那么这里的问题是什么?我该如何解决?
我非常感谢你们的任何想法或建议......
提前致谢。
【问题讨论】:
-
首先您需要迁移
users和wallets表,然后迁移user_wallet_transactions。 -
列的类型必须相同,
bigIncrements()创建一个“UNSIGNED BIGINT”列,而不是“unsignedSmallInteger”。 laravel.com/docs/5.8/migrations#columns -
@sta
wallets&users已迁移。 -
@brombeer 我将
$table->unsignedSmallInteger('user_id');&$table->unsignedSmallInteger('wallet_id');更改为` $table->bigIncrements('user_id');` &$table->bigIncrements('wallet_id');但没有解决问题 -
应该是
unsignedBigIntegerex :$table->unsignedBigInteger('user_id');和$table->unsignedBigInteger('wallet_id');这可以解决你的问题
标签: php laravel migration laravel-5.8 laravel-migrations