You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel使用hasMany关联查询报education表不存在如何解决

Laravel关联查询表不存在报错排查方案

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'doctor1.education' doesn't exist (SQL: select * from education where education.dr_id in (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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.02 01:45:52