Laravel关联查询报order_products表不存在,模型文件名该改为何?
Laravel关联查询报错:表
order_products不存在的解决方案 问题背景
现有数据库表order_product,对应模型文件名为order_product,模型代码:
public $timestamps = false; protected $fillable = [ 'order_id', 'product_id', 'amount', ];
Order模型代码片段:
public $timestamps = true; protected $fillable = [ 'order_number', 'client_id', 'description', ]; public function client() { return $this->belongsTo(Client::class); } public function products() { return $this->belongsToMany(Product::class); } public function orders() { return $this->belongsToMany(order_product::class); }
控制器执行代码:
$orders = Order::where('id', $id)->firstOrFail(); $orders->load('client', 'products','orders');
触发报错:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'user_project_db.order_products' doesn't exist
核心解决方案
模型文件重命名
将order_product.php模型文件重命名为**OrderProduct.php**,同时将模型类名修改为OrderProduct(遵循Laravel大驼峰命名规范):
class OrderProduct extends Model { public $timestamps = false; protected $fillable = [ 'order_id', 'product_id', 'amount', ]; // 必加:因实际表名为单数`order_product`,需手动指定表名(Laravel默认将模型名复数化作为表名) protected $table = 'order_product'; }
修正Order模型关联
修改Order模型中的orders关联方法(建议重命名为orderProducts避免命名混淆),并引用正确的模型类:
public function orderProducts() { return $this->belongsToMany(OrderProduct::class); }
调整控制器调用
同步修改控制器中的关联加载代码:
$orders->load('client', 'products','orderProducts');
报错原因说明
Laravel默认遵循「模型名大驼峰,表名复数下划线」的命名约定:当使用不符合规范的模型名order_product时,框架会错误推断表名为order_products(复数形式),但实际数据库表是order_product,因此触发表不存在的错误。修正模型命名并指定表名后,框架才能正确匹配到实际数据表。
内容的提问来源于stack exchange,提问作者laraCoder
相关产品推荐
相关产品推荐

