Laravel关联查询同名字段覆盖问题
在 Laravel Eloquent ORM 执行 join 关联查询操作时,如果参与连接的两张表包含名称相同的字段(例如 id),框架默认会将后出现的同名字段的值覆盖先前的值,从而导致返回的数据不符合预期。以下是一个典型的关联查询场景示例:
PHP
$priority = Priority::rightJoin('touch', 'priorities.touch_id', '=', 'touch.id')
->where('priorities.type', 1)
->orderBy('priorities.total_score', 'desc')
->orderBy('touch.created_at', 'desc')
->get();
$priority = Priority::rightJoin('touch', 'priorities.touch_id', '=', 'touch.id')
->where('priorities.type', 1)
->orderBy('priorities.total_score', 'desc')
->orderBy('touch.created_at', 'desc')
->get();
假设 priorities 表和 touch 表均包含 id 字段,若按照常规方式构造上述查询语句,最终返回的查询结果如图所示:

Laravel 关联查询返回错误的 id
观察发现,返回结果中的 id 值并非来自 priorities 表,而是被 touch 表的 id 字段所覆盖。若打印出实际执行的 SQL 语句进行分析:
select * from `priorities`
right join `touch`
on `priorities`.`touch_id` = `touch`.`id`
where `priorities`.`type` = '1'
order by `priorities`.`total_score` desc, `touch`.`created_at` desc
select * from `priorities`
right join `touch`
on `priorities`.`touch_id` = `touch`.`id`
where `priorities`.`type` = '1'
order by `priorities`.`total_score` desc, `touch`.`created_at` desc
查询结果如图:

从纯 SQL 查询的角度来看,结果是正确的,因为数据库将另一张表中重名的 id 字段默认重命名为 id1。然而,Laravel 返回的 id 值并未对应图中的 id1 字段,而是被另一张表中重名的字段值意外覆盖了。
解决这一问题的方法是添加 select 方法以明确指定需要获取的字段。修正后的查询语句构造代码如下:
PHP
$priority = Priority::select(['priorities.*', 'touch.name', 'touch.add_user'])
->rightJoin('touch', 'priorities.touch_id', '=', 'touch.id')
->where('priorities.type', 1)
->orderBy('priorities.total_score', 'desc')
->orderBy('touch.created_at', 'desc')
->get();
$priority = Priority::select(['priorities.*', 'touch.name', 'touch.add_user'])
->rightJoin('touch', 'priorities.touch_id', '=', 'touch.id')
->where('priorities.type', 1)
->orderBy('priorities.total_score', 'desc')
->orderBy('touch.created_at', 'desc')
->get();
通过上述修改即可解决该问题。因此在后续开发中需注意,当使用 Laravel 对两张表进行 join 操作时,最好显式指定返回字段以避免此类冲突。
这是否属于 Laravel 的一个 Bug 呢?当一个字段的值被同名字段覆盖时,系统应当抛出错误或警告,而不是静默地继续执行下去。
GitHub 上已有用户提出相同的问题,官方作者也提供了解决方案,但并未给出其他更优的处理策略。
Laravel 版本:5.3
链接:https://github.com/laravel/framework/issues/4962
以上所述是小编给大家介绍的Laravel 关联查询返回错误的 id的解决方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对本站网站的支持!