iT邦幫忙

0

laravel whereHas 跨DB 存取問題

最近寫到一段code,是要讓前端用keyword搜尋出資料:

            Table1Model::with('table2','table3')
            ->where(function($query)  use ($keyword){
                return $query->orWhere('a', 'like', "%$keyword%")
                ->orWhere('b', 'like', "%$keyword%");
            })
            ->orWhereHas('table3',function($query) use ($keyword){
                return $query->where('c','like', "%$keyword%");
            })

我是Laravel 5.5 版本

但這樣查詢之後發現whereHas那段會出錯
因為table2 的 database 和 Table1Model 是不一樣的,而預設會去找Table1Model的database (我這裡假設是DatabaseA),當然那裏的databse 並沒有table2
而就算我在table2 的connection 有填入正確的database(我這裡假設是DatabaseB) 也都沒有用

上網有查到一些類似的問題:
https://laracasts.com/discuss/channels/eloquent/using-wherehas-across-two-databases
https://stackoverflow.com/questions/27394675/laravel-wherehas-across-two-separate-databases

而後面我發現只要在table2 Model 這裡的table 做一些修改


class table2 extends Model
{
    use SoftDeletes;

    protected $table = "databaseB.table2";
    public $incrementing = false;

    protected $connection = 'mysql2';
    protected $keyType = "string";

    protected $dates = [
        'firstLoginTime',
        'lastLoginTime',
        'created_at',
        'updated_at',
        "deleted_at"
    ];
    ....(略)
  }

就能夠解決whereHas table2找不到正確的database 的問題,也就是whereHas cross DB的問題...

我猜可能是因為Laravel ORM在轉換成sql 時,剛好讀到我這個table 裡面的字串, 以至於他能找到正確的Database 去撈表

但因為只是已經上線,確定的專案, 修改基礎的Model 有點令人感覺很抖
雖然有試過似乎其他功能都正常沒有影響

但還是想放上來問問大大們這樣是否可行?
或者有沒有能夠處理這種whereHas 跨DB的問題?
(就算我在model 裡面填寫正確的$connection 也沒有應用到whereHas 那裏耶)

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

1
firecold
iT邦新手 1 級 ‧ 2020-07-07 17:38:01
最佳解答

為什麼你都還沒用過whereHas就要下orWhereHas呢?
你這樣下主要Model 是table1
然後whereHas下在第一層也就是table1
所以判斷的不是table2這很正常阿

我要發表回答

立即登入回答