Laravel 10 记录一次 多对多关联由于表名问题(英文语法转换)导致的查询不到bug

发布时间 2023-08-21 21:52:45作者: 夏秋初

参考

环境

软件/系统 版本 说明
windows 10
php 8.1.9-Win32-vs16-x64
composer 2.5.5
laravel ^10.10
mysql 8.0.28

正文

多对多查询,定义了三张表:maps,map_monster_category,monster_categorys, 其中map_monster_category为两表的中间表包含:map_id,monster_category_id
按照网上教程查询不到数据,表名规则和Laravel文档内一致,通过查询SQL发现表名被按照英语语法复数形式进行了转换,转换后的sql为:

select
  `monster_categories`.*,
  `map_monster_category`.`map_id` as `pivot_map_id`,
  `map_monster_category`.`monster_category_id` as `pivot_monster_category_id`
from
  `monster_categories`
  inner join `map_monster_category` on `monster_categories`.`id` = `map_monster_category`.`monster_category_id`
where
  `map_monster_category`.`map_id` in (1)

其中的 monster_categorys 被转换成为了 monster_categories.

解决办法

  1. 按照英文语法设置表名
  2. 在模型中手动指定表名。
class MonsterCategory extends Model
{
    use HasFactory;
    /**
     * 数据表名称
     */
    protected $table = 'monster_categorys';
}