最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

PHP中Laravel 關(guān)聯(lián)查詢返回錯誤id的解決方法

 更新時間:2017年04月01日 09:38:03   投稿:mrr  
這篇文章主要介紹了Laravel 關(guān)聯(lián)查詢返回錯誤id的解決方法,非常不錯,具有參考借鑒價值,需要的朋友參考下吧

在 Laravel Eloquent 中使用 join 關(guān)聯(lián)查詢,如果兩張表有名稱相同的字段,如 id,那么它的值會默認被后來的同名字段重寫,返回不是期望的結(jié)果。例如以下關(guān)聯(lián)查詢:

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 字段,如果這樣構(gòu)造查詢的話,返回的查詢結(jié)果如圖:

Laravel 關(guān)聯(lián)查詢返回錯誤的 id

Laravel 關(guān)聯(lián)查詢返回錯誤的 id

這里 id 的值不是 priorities 表的 id 字段,而是 touch 表的 id 字段,如果打印出執(zhí)行的 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

查詢結(jié)果如圖:

使用 sql 查詢的結(jié)果實際上是對的,另外一張表重名的 id 字段被默認命名為 id1,但是 Laravel 返回的 id 的值卻不是圖中的 id 字段,而是被重名的另外一張表的字段重寫了。

解決辦法是加一個 select 方法指定字段,正確的構(gòu)造查詢語句的代碼:

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 呢?如果一個字段的值被同名的字段值重寫了,這種情況要不要報一個錯誤出來,而不能默認繼續(xù)執(zhí)行下去。

github 上有人也提出了同樣的問題,作者也提供了解決辦法,但并沒其他更好的方案。

Laravel 版本:5.3

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

以上所述是小編給大家介紹的Laravel 關(guān)聯(lián)查詢返回錯誤的 id的解決方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!

相關(guān)文章

最新評論

年辖:市辖区| 楚雄市| 商河县| 呼伦贝尔市| 奎屯市| 天台县| 平原县| 公主岭市| 临沂市| 潜山县| 信阳市| 宜春市| 虞城县| 汪清县| 碌曲县| 大姚县| 芦溪县| 安达市| 伊吾县| 名山县| 长岭县| 榆中县| 丰城市| 子洲县| 台山市| 刚察县| 沈阳市| 筠连县| 巴林左旗| 西平县| 读书| 成都市| 澜沧| 双城市| 马鞍山市| 额敏县| 德清县| 新安县| 碌曲县| 镇原县| 健康|