手机版

PHP中Laravel关联查询返回错误id的解决方案

时间:2021-09-05 来源:互联网 编辑:宝哥软件园 浏览:

在Laravel English中使用联接关联查询。如果两个表具有相同名称的字段,例如id,那么默认情况下,它们的值将被后面具有相同名称的字段覆盖,并且将返回意外的结果。例如,以下相关查询:

服务器端编程语言(Professional Hypertext Preprocessor的缩写)

$ priority=priority :3360 right join(' touch ',' priorities.touch_id ','=',' touch . id ')-其中(' priorities.type ',1)-order by(' priorities . total _ score ',' desc ')-order by(' touch . created _ at ',' desc ')-get();$ priority=priority :3360 right join(' touch ',' priorities.touch_id ','=',' touch . id ')-其中(' priorities.type ',1)-order by(' priorities . total _ score ',' desc ')-order by(' touch . created _ at ',' desc ')-get();优先级和触摸表都有id字段。如果以这种方式构造查询,返回的查询结果如下:

Laravel  关联查询返回错误的 id

Laravel关联查询返回了错误的id

这里id的值不是优先级表的id字段,而是触摸表的id字段。如果打印了执行的sql语句:

从“优先级”中选择*在“优先级”上右连接“触摸”。“触摸_ id ”=“触摸”。“id ”,其中“优先级”。“类型”=“1”按“优先级”排序。“total _ score ”, desc,“触摸”。“_ at` descselect *在“优先级”上右连接“触摸”。“触摸_ id ”=“触摸”。“id ”,其中“优先级”。“类型”=“1”按“优先级”排序。` total _ score `desc,` touch`。` created _ at `desc。查询结果如下:

sql查询的结果实际上是正确的。另一个同名表的id字段默认命名为id1,但Laravel返回的id值不是图中的id字段,而是被另一个同名表的字段重写了。

解决方案是添加一个select方法来指定字段,并正确构造查询语句的代码:

服务器端编程语言(Professional Hypertext Preprocessor的缩写)

$ priority=priority :3360 select([' priorities。*、' touch.name '、' touch . add _ user '])-right join(' touch '、' priorities.touch_id '、'='、' touch . id ')-其中(' priorities.type ',1)-order by(' priorities . total _ score '、' desc ')-order by(' touch . created _ at '、' desc ')-get();$ priority=priority :3360 select([' priorities。*、' touch.name '、' touch . add _ user '])-right join(' touch '、' priorities.touch_id '、'='、' touch . id ')-其中(' priorities.type ',1)-order by(' priorities . total _ score '、' desc ')-order by(' touch . created _ at '、' desc ')-get();这就解决了问题,所以以后要注意。最好指定当两个Laravel表连接时返回的字段。

这是Laravel的bug吗?如果字段的值被同名字段的值覆盖,是否应该报告错误而不是默认情况下继续?

github上也有人提出了同样的问题,作者也提供了解决方案,但是没有更好的解决方案。

Laravel版本:5.3

链接:https://github.com/laravel/framework/issues/4962

以上就是边肖介绍的Laravel关联查询返回错误id的解决方案。希望对大家有帮助。如果你有任何问题,请给我留言,边肖会及时回复你。非常感谢您对我们网站的支持!

版权声明:PHP中Laravel关联查询返回错误id的解决方案是由宝哥软件园云端程序自动收集整理而来。如果本文侵犯了你的权益,请联系本站底部QQ或者邮箱删除。