问题描述
我正在尝试创建广告表,其中包含引用了用户表中“ id”列的“ user_id”列,但是没有运气。
从错误消息开始,我注意到框架没有传递users表的'id'列。知道我要使用“ PHPMyAdmin”手动解决此问题。
Users Schema:
Schema::create('users',function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
Advertisements Schema:
Schema::create('advertisements',function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->string('name');
$table->text('description');
$table->mediumtext('image')->nullabe;
$table->timestamps();
$table->foreign('user_id')
->reference('id')
->on('users')
->onDelete('cascade');
});
错误:
PDOException::("sqlSTATE[42000]: Syntax error or access violation: 1064 You have an error in your sql Syntax; check the manual that corresponds to your MariaDB server version for the right Syntax to use near ') on delete cascade' at line 1").
PDO::prepare("alter table `advertisements` add constraint `advertisements_user_id_foreign` foreign key (`user_id`) references `users` () on delete cascade")
解决方法
问题出在您的Advertisements迁移代码中,应将其放在-> references('id')而不是-> reference('id') >
Advertisements Schema:
Schema::create('advertisements',function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->string('name');
$table->text('description');
$table->mediumtext('image')->nullabe;
$table->timestamps();
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
});