怎么解决Laravel关联查询返回错误id的问题
发表于:2025-11-10 作者:千家信息网编辑
千家信息网最后更新 2025年11月10日,这篇文章主要介绍了怎么解决Laravel关联查询返回错误id的问题的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇怎么解决Laravel关联查询返回错误id的问题文章都会有
千家信息网最后更新 2025年11月10日怎么解决Laravel关联查询返回错误id的问题
这篇文章主要介绍了怎么解决Laravel关联查询返回错误id的问题的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇怎么解决Laravel关联查询返回错误id的问题文章都会有所收获,下面我们一起来看看吧。
在 Laravel Eloquent 中使用 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 表的 id 字段,而是 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 的值却不是图中的 id 字段,而是被重名的另外一张表的字段重写了。
解决办法是加一个 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关联查询返回错误id的问题"这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对"怎么解决Laravel关联查询返回错误id的问题"知识都有一定的了解,大家如果还想学习更多知识,欢迎关注行业资讯频道。
查询
字段
关联
错误
问题
结果
知识
内容
篇文章
而是
语句
如图
相同
代码
价值
办法
名称
实际
实际上
操作简单
数据库的安全要保护哪些东西
数据库安全各自的含义是什么
生产安全数据库录入
数据库的安全性及管理
数据库安全策略包含哪些
海淀数据库安全审计系统
建立农村房屋安全信息数据库
易用的数据库客户端支持安全管理
连接数据库失败ssl安全错误
数据库的锁怎样保障安全
商品网站数据库模型
网网络安全手抄报的内容
软件开发 职业规划
数据库学生管理系统.net
武大网络安全2022年招生科目
网络安全小报电子
类似于微信这种软件开发难吗
集美大学网络安全中心
互联网基金和科技基金
如何选择合适的数据库
松江区网络技术咨询服务价钱
浙江电话软件开发供应
服务器面试
通ysql更新数据库
oracle登录指定数据库
软件开发java编程复杂吗
国企网络安全网站
网络安全人人有责论文
民政部门负责协调网络安全
打拐数据库是什么时候成立的
软件开发公司招聘政审吗
工信部 网络安全局
我的世界脏小豆骗赞服务器
怎么设置数据库输入记录
研发arm服务器芯片
电脑提示目前没有服务器登录
河南省网络安全法
木瓜互联网科技布沙发清洗机
北京电信网络安全岗工资
神通数据库安装