温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

PHP中Laravel关联查询返回错误id如何解决

发布时间:2022-12-07 10:03:44 来源:亿速云 阅读:89 作者:iii 栏目:编程语言

这篇文章主要介绍了PHP中Laravel关联查询返回错误id如何解决的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇PHP中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 字段,如果这样构造查询的话,返回的查询结果如图:

PHP中Laravel关联查询返回错误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

查询结果如图:

PHP中Laravel关联查询返回错误id如何解决

使用 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 两张表 join 的时候返回的字段最好要指定。

关于“PHP中Laravel关联查询返回错误id如何解决”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“PHP中Laravel关联查询返回错误id如何解决”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI