Laravel执行php artisan db:seed后报1054未知列错误如何解决?
问题解决:Laravel 数据填充时「Column not found: 1054」错误
错误原因
从报错的SQL语句能看到,系统在查找page_id (注意字段名末尾有空格)这个字段,但你的数据库表中实际存在的是page_id字段——问题出在你的DatabaseSeeder代码里,填充CarouselSection时字段名写成了'page_id ',多了一个末尾空格,导致数据库匹配不到正确字段。
修复方法
修改DatabaseSeeder中的字段名,去掉page_id后面的空格:
class DatabaseSeeder extends Seeder { /** * Seed the application's database. * * @return void */ public function run() { \App\Models\Page::factory()->create([ 'page_name_en' => 'Home' ]); \App\Models\CarouselSection::factory()->create([ 'page_id' => 1, // 移除末尾空格 'order' => 1, 'slide_no' => 1, 'image' => null, 'title_en' => 'Fisrt Title', 'short_title_en' => 'first short title', 'button_text_en' => 'learn more', 'button_link' => 'www.google.com' ]); } }
额外优化建议
- 避免硬编码
page_id为1,可先获取创建的Page实例再关联赋值,提升代码可靠性:
$homePage = \App\Models\Page::factory()->create([ 'page_name_en' => 'Home' ]); \App\Models\CarouselSection::factory()->create([ 'page_id' => $homePage->id, // 其他字段保持不变 ]);
- 给模型添加关联关系,方便后续业务操作:
在Page模型中添加:
在public function carouselSections() { return $this->hasMany(CarouselSection::class); }CarouselSection模型中添加:public function page() { return $this->belongsTo(Page::class); }
内容的提问来源于stack exchange,提问作者Mustafa Alawami
相关产品推荐
相关产品推荐

