SQLSTATE[HY000]: General error: 3734 Failed to add the foreign key constraint. Missing column 'id' for constraint 'posts_user_id_foreign' in the referenced table 'users' (SQL: alter table `posts` add constraint `posts_user_id_foreign` foreign key (`user_id`) references `users` (`id`))
at D:\multimedia-projects-main (1)\multimedia-projects-main\jobsearch\vendor\laravel\framework\src\Illuminate\Database\Connection.php:761
757▕ // If an exception occurs when attempting to run a query, we'll format the error
758▕ // message to include the bindings with SQL, which will make this exception a
759▕ // lot more helpful to the developer instead of just the database's errors.
760▕ catch (Exception $e) {
➜ 761▕ throw new QueryException(
762▕ $query, $this->prepareBindings($bindings), $e
763▕ );
764▕ }
765▕ }
1 D:\multimedia-projects-main (1)\multimedia-projects-main\jobsearch\vendor\laravel\framework\src\Illuminate\Database\Connection.php:546
PDOException::("SQLSTATE[HY000]: General error: 3734 Failed to add the foreign key constraint. Missing column 'id' for constraint 'posts_user_id_foreign' in the referenced table 'users'")
2 D:\multimedia-projects-main (1)\multimedia-projects-main\jobsearch\vendor\laravel\framework\src\Illuminate\Database\Connection.php:546
PDOStatement::execute()
外部公共函数up()的代码如下所示
{
Schema::create('posts', function (Blueprint $table) {
$table->id('post_id')->unique()->nullable(false);
$table->biginteger('user_id')->unasigned()->index();
$table->biginteger('company_id')->unasigned()->index();
$table->biginteger('job_id')->unasigned()->index();
$table->timestamps();
});
Schema::table('posts', function($table) {
$table->foreign('user_id')->references('id')->on('users');
$table->foreign('company_id')->references('id')->on('companies');
$table->foreign('job_id')->references('id')->on('jobs');
});
}
这是给用户的
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id('user_id');
$table->string('name');
$table->string('email')->unique();
$table->foreignid('companyid');
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
其余的都差不多
已经尝试将外键更改为大整数和整数,已经尝试更改外部引用的名称,但仍然不起作用
1条答案
按热度按时间ryoqjall1#
如果你在
$schema->id()
函数中传递一个参数,列将以给定的参数命名。在你的代码中,你已经重命名了
users
表中的id
列。不要使用$table->id('user_id');
,而是使用$table->id();
,这将生成名为id
的列。或者,如果要将
users
表中的主键列命名为user_id
,则必须更改外键的设置方式: