在 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 两张表 join 的时候返回的字段最好要指定。
这算不算是 Laravel 的一个 bug 呢?如果一个字段的值被同名的字段值重写了,这种情况要不要报一个错误出来,而不能默认继续执行下去。
github 上有人也提出了同样的问题,作者也提供了解决办法,但并没其他更好的方案。
Laravel 版本:5.3
链接:https://github.com/laravel/framework/issues/4962
以上所述是小编给大家介绍的Laravel 关联查询返回错误的 id的解决方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
稳了!魔兽国服回归的3条重磅消息!官宣时间再确认!
昨天有一位朋友在大神群里分享,自己亚服账号被封号之后居然弹出了国服的封号信息对话框。
这里面让他访问的是一个国服的战网网址,com.cn和后面的zh都非常明白地表明这就是国服战网。
而他在复制这个网址并且进行登录之后,确实是网易的网址,也就是我们熟悉的停服之后国服发布的暴雪游戏产品运营到期开放退款的说明。这是一件比较奇怪的事情,因为以前都没有出现这样的情况,现在突然提示跳转到国服战网的网址,是不是说明了简体中文客户端已经开始进行更新了呢?
更新日志
- 纯音入心系列纯音乐《天籁古筝》1CD[MP3][331MB]
- 男女对唱典藏天碟《发烧对唱·那个季节里的歌DSD》10CD[WAV]
- 群星2010-歌林精选辑[歌林][WAV+CUE]
- TrioZimbalist-PianoTriosofWeinberg,Auerbach,Dvorak(2024)[24-44,1]wav
- 群星.1992-滚石第一流台湾歌·12王牌大车拼【滚石】【WAV+CUE】
- 林子祥.1984-创作歌集【华纳】【WAV+CUE】
- 周汤豪.2010-周汤豪【华纳】【FLAC分轨】
- Mozart-TheStringQuintets-AmadeusQuartet,CecilAronowitz(2017)[24-44,1][WAV+CUE]
- JamesWilliamsDennisIrwin-Focus(2024,Red)[24-48]FLAC
- 藤泽麻衣《空みあげて》[WAV]
- 纯音入心系列纯音乐《中国古筝经典名曲》1CD[MP3][1.3GB]
- 纯音入心系列纯音乐《古筝新奏:岁月静好与筝语,细水流年与筝同》1CD[MP3][846.9MB]
- 670《脆弱敏感小女生》[320K/MP3][27.53MB]
- 曾琳.2011-好好爱我【南方】【WAV+CUE】
- 范晓萱.1995-RAIN【福茂】【WAV+CUE】