gpt4 book ai didi

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

转载 作者:qq735679552 更新时间:2022-09-28 22:32:09 25 4
gpt4 key购买 nike

CFSDN坚持开源创造价值,我们致力于搭建一个资源共享平台,让每一个IT人在这里找到属于你的精彩世界.

这篇CFSDN的博客文章PHP中Laravel 关联查询返回错误id的解决方法由作者收集整理,如果你对这篇文章有兴趣,记得点赞哟.

在 laravel eloquent 中使用 join 关联查询,如果两张表有名称相同的字段,如 id,那么它的值会默认被后来的同名字段重写,返回不是期望的结果。例如以下关联查询:

php 。

?
1
2
3
4
5
$priority = priority::rightjoin( 'touch' , 'priorities.touch_id' , '=' , 'touch.id' )
  ->where( 'priorities.type' , 1)
  ->orderby( 'priorities.total_score' , 'desc' )
  ->orderby( 'touch.created_at' , 'desc' )
  ->get();
?
1
2
3
4
5
$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 语句:

?
1
2
3
4
5
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
?
1
2
3
4
5
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 。

?
1
2
3
4
5
6
$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();
?
1
2
3
4
5
6
$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的解决方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对我网站的支持! 。

原文链接:https://blog.tanteng.me/2017/03/laravel-model-join-wrong-id/?utm_source=tuicool&utm_medium=referral 。

最后此篇关于PHP中Laravel 关联查询返回错误id的解决方法的文章就讲到这里了,如果你想了解更多关于PHP中Laravel 关联查询返回错误id的解决方法的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com