Laravel 10 记录一次 多对多关联由于表名问题(英文语法转换)导致的查询不到bug
参考
- https://segmentfault.com/q/1010000018450663
- https://learnku.com/docs/laravel/10.x/eloquent-relationships/14889#a93d4c
- https://learnku.com/docs/laravel/10.x/eloquent-relationships/14889#6bf722 获取中间表的字段 withPivot
环境
软件/系统 | 版本 | 说明 |
---|---|---|
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
.
解决办法
- 按照英文语法设置表名
- 在模型中手动指定表名。
class MonsterCategory extends Model
{
use HasFactory;
/**
* 数据表名称
*/
protected $table = 'monster_categorys';
}
转载时请带上原文链接,谢谢。
博 主 :夏秋初
地 址 :https://www.cnblogs.com/xiaqiuchu/p/17647186.html
博 主 :夏秋初
地 址 :https://www.cnblogs.com/xiaqiuchu/p/17647186.html