首頁 > 後端開發 > php教程 > PHP中Laravel 關聯查詢傳回錯誤id的解決方法詳解

PHP中Laravel 關聯查詢傳回錯誤id的解決方法詳解

墨辰丷
發布: 2023-03-27 19:04:02
原創
1716 人瀏覽過

這篇文章主要介紹了Laravel 關聯查詢返回錯誤id的解決方法,非常不錯,具有參考借鑒價值,需要的朋友參考下吧

在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

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

以上就是本文的全部內容,希望對大家的學習有所幫助。


相關推薦:

PHP處理蘋果APP內購後到服務端的二次驗證(專案經驗)

DVWA之php mysql手工注入

#PHP專案整合微信端掃碼支付API(境內支付)

#

以上是PHP中Laravel 關聯查詢傳回錯誤id的解決方法詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
最新問題
composer安裝laravel安裝不上
來自於 1970-01-01 08:00:00
0
0
0
Laravel 5.1 登入 laravel 自備的 沒有啦
來自於 1970-01-01 08:00:00
0
0
0
Laravel Space/laravel-backup 無法安裝
來自於 1970-01-01 08:00:00
0
0
0
為什麼thinkphp比laravel效能好?
來自於 1970-01-01 08:00:00
0
0
0
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板