laravel 8执行数据库迁移文件出错的原因和解决方案
背景:
laravel 8 ,要迁移的mysql表数据结构如下:
cars表:
+-------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------+--------------+------+-----+---------+----------------+ | id | int unsigned | NO | PRI | NULL | auto_increment | | name | varchar(255) | NO | | NULL | | | founded | int | NO | | NULL | | | description | longtext | NO | | NULL | | | created_at | timestamp | YES | | NULL | | | updated_at | timestamp | YES | | NULL | | +-------------+--------------+------+-----+---------+----------------+
car_models表:
+------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------+--------------+------+-----+---------+----------------+ | id | int unsigned | NO | PRI | NULL | auto_increment | | car_id | int unsigned | NO | MUL | NULL | | | model_name | varchar(255) | NO | | NULL | | | created_at | timestamp | YES | | NULL | | | updated_at | timestamp | YES | | NULL | | +------------+--------------+------+-----+---------+----------------+
执行 php artisan migrate ,报错:SQLSTATE[HY000]: General error: 3780 Referencing column 'car_id' and referenced column 'id' in foreign key constraint 'car_models_car_id_foreign' are incompatible.
分析:根据提示,可以看出是说car_id和id不兼容,导致这个问题的原因是laravel 8 生成的migration里,默认使用的是$table->id(),需要改成$table->increment('id')