黑松山资源网 Design By www.paidiu.com
在 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的解决方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!
黑松山资源网 Design By www.paidiu.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
黑松山资源网 Design By www.paidiu.com
暂无评论...
更新日志
2025年03月05日
2025年03月05日
- 小骆驼-《草原狼2(蓝光CD)》[原抓WAV+CUE]
- 群星《欢迎来到我身边 电影原声专辑》[320K/MP3][105.02MB]
- 群星《欢迎来到我身边 电影原声专辑》[FLAC/分轨][480.9MB]
- 雷婷《梦里蓝天HQⅡ》 2023头版限量编号低速原抓[WAV+CUE][463M]
- 群星《2024好听新歌42》AI调整音效【WAV分轨】
- 王思雨-《思念陪着鸿雁飞》WAV
- 王思雨《喜马拉雅HQ》头版限量编号[WAV+CUE]
- 李健《无时无刻》[WAV+CUE][590M]
- 陈奕迅《酝酿》[WAV分轨][502M]
- 卓依婷《化蝶》2CD[WAV+CUE][1.1G]
- 群星《吉他王(黑胶CD)》[WAV+CUE]
- 齐秦《穿乐(穿越)》[WAV+CUE]
- 发烧珍品《数位CD音响测试-动向效果(九)》【WAV+CUE】
- 邝美云《邝美云精装歌集》[DSF][1.6G]
- 吕方《爱一回伤一回》[WAV+CUE][454M]