网创优客建站品牌官网
为成都网站建设公司企业提供高品质网站建设
热线:028-86922220
成都专业网站建设公司

定制建站费用3500元

符合中小企业对网站设计、功能常规化式的企业展示型网站建设

成都品牌网站建设

品牌网站建设费用6000元

本套餐主要针对企业品牌型网站、中高端设计、前端互动体验...

成都商城网站建设

商城网站建设费用8000元

商城网站建设因基本功能的需求不同费用上面也有很大的差别...

成都微信网站建设

手机微信网站建站3000元

手机微信网站开发、微信官网、微信商城网站...

建站知识

当前位置:首页 > 建站知识

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

这篇文章主要介绍了PHP中Laravel关联查询返回错误id如何解决的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇PHP中Laravel关联查询返回错误id如何解决文章都会有所收获,下面我们一起来看看吧。

宝坻网站制作公司哪家好,找创新互联!从网页设计、网站建设、微信开发、APP开发、响应式网站等网站项目制作,到程序开发,运营维护。创新互联自2013年起到现在10年的时间,我们拥有了丰富的建站经验和运维经验,来保证我们的工作的顺利进行。专注于网站建设就选创新互联。

在 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如何解决”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注创新互联行业资讯频道。


分享标题:PHP中Laravel关联查询返回错误id如何解决
转载源于:http://bjjierui.cn/article/pcccji.html

其他资讯