這篇文章主要介紹了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
這裡 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
以上就是本文的全部內容,希望對大家的學習有所協助。