Laravel Eloquent 模型進行多表關聯查詢,爲了將主表也能使用別名,我們使用了:
->from('users as u')
這個方法,可以將主表也可以使用別名了
但是,使用軟刪除時,又會報錯:
Column not found: 1054 Unknown column users.deleted_at
略微思索下,應該就是,軟刪除方法,使用的是主表的 '表名',而非是我們自己定義的 '別名'。
本打算查看下源碼,想了下,還是搜索下,因爲這應該是一個常見問題。
找個篇文章,不錯:
https://learnku.com/articles/16442/laravel-model-uses-soft-delete-left-join-query-table-alias
解決問題:
原因:軟刪除拼接的 where 條件的字段:
return $this->getTable().'.'.$column;
解決方法:
使用 setTable('u') 來設置下數據表
這裏還得注意下:
我的原始代碼:
User::from('users as u')
第一次使用:
User::from('users as u')
->setTable('u')
報錯:
Call to undefined method Illuminate\Database\Eloquent\Builder::setTable()
原因:
User::from() 後返回的是 Builder 類,而 setTable() 定義在 Model 類
第二次使用:
更換下:
from() 和 setTable() 位置
User::setTable('u')
->from('users as u')
報錯:
Non-static method Illuminate\Database\Eloquent\Model::setTable() should not be called statically
原因:
setTable() 不能靜態調用
最終:
(new User())
->setTable('u')
->from('users as u')
還挺波折的,這個解決方法必須記住