Laravel使用hasMany关联查询报education表不存在如何解决
Laravel关联查询表不存在报错排查方案
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'doctor1.education' doesn't exist (SQL: select * from
educationwhereeducation.dr_idin (1))
现有实现代码
- Doctor模型(对应
doctors数据表)关联定义:
public function educations(){ return $this->hasMany('App\Models\Education','dr_id'); }
- Education模型(对应
educations数据表)关联定义:
public function doctor(){ return $this->belongsTo('App\Models\Doctor','dr_id'); }
- 控制器查询逻辑:
public function profilesetting(){ $userinfo = Doctor::with('educations')->where('id','=',session('drid'))->get(); dd($userinfo); }
报错根因
Eloquent模型默认遵循「类名蛇形复数」的表名映射规则,Education模型默认会映射到单数命名的education表,但实际业务创建的表为复数形式的educations,框架找不到对应表抛出错误。
解决步骤
- 校验数据库表:确认
doctor1库下存在educations表,若不存在先执行建表迁移补全表结构。 - 手动指定Education模型对应表名:在Education模型类中添加
$table属性,覆盖默认表名映射规则,示例代码如下:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Education extends Model { // 绑定实际业务表名 protected $table = 'educations'; public function doctor(){ return $this->belongsTo(Doctor::class,'dr_id'); } }
- 功能验证:重新触发控制器请求,此时框架生成的关联查询SQL会自动读取
educations表数据,报错消失。
额外校验项:若修复表名后仍有报错,核对educations表中dr_id字段是否存在、字段类型与doctors表主键id类型是否匹配即可。
内容的提问来源于stack exchange,提问作者ITS_HJ 24
相关产品推荐
相关产品推荐

