2017-05-17 47 views
0

我有一個表,我正在運行搜索。富。我想檢查搜索詞是否像表中的一堆不同的字段。但我希望結果被強制爲「積極」。如何強制拉拉維爾集合的where子句5

我使用Laravel 5.0

$foos = DB::table('foo') 
     ->where('name', 'LIKE', '%' . $query . '%') 
     ->orWhere('description', 'LIKE', '%' . $query . '%') 
     ->orWhere('address_city', 'LIKE', '%' . $query . '%') 
     ->orWhere('short_description', 'LIKE', '%' . $query . '%') 
     ->orWhere('interview', 'LIKE', '%' . $query . '%') 
     ->get(); 

    $foos = $foos->where('active', true)->get(); 
+1

把' - >在哪裏( '主動',真)'之前,你的第一個'where'不起作用? –

+0

就是這樣。謝謝 –

+0

對我來說似乎很奇怪,你希望在返回的'Collection'上有一個where子句,而不是在數據庫查詢中增加另一個where子句。 –

回答

0

收藏有類似查詢構建器中where方法。

$activeFoos = $foos->where('active', true); 

https://laravel.com/docs/5.4/collections#method-where

編輯: 我明白你現在從註釋需要。嘗試下面的代碼,並且還請注意,我將您的原始$查詢更改爲$ find。所以記住這一點。

$foos = DB::table('foo') 
    ->where('active', true) 
    ->where(function ($query) use ($find) { 
     $query->where('name', 'LIKE', "%{$find}%") 
      ->orWhere('description', 'LIKE', "%{$find}%") 
      ->orWhere('address_city', 'LIKE', "%{$find}%") 
      ->orWhere('short_description', 'LIKE', "%{$find}%") 
      ->orWhere('interview', 'LIKE', "%{$find}%"); 
    }) 
    ->get(); 
+0

如果你看那是我正在嘗試,它會返回一個錯誤 –

+0

你可以看到我已經刪除了 - > get()'? – Sandeesh

+0

我正在使用laravel 5.0 –

0

active實際真或只是truthy的值(例如1-3的整數)?

對於寬鬆比較,您需要使用whereLoose('active', true),否則Laravel的方法將在Collection中執行嚴格的類型比較。 ()是一個查詢生成器方法,其中()方法返回一個新的集合而不是一個生成器實例,因此需要移除get()。

+0

該值實際上是一個int:1.但是,如果我將whereActive(1)傳遞給主查詢,它仍會獲得一些whereActive = 0。 –

0

你在做什麼是錯的。您檢索一組數據,然後嘗試添加一個where claus,然後嘗試再次檢索它。所以這樣做:

$foos = DB::table('foo') 
     ->where('name', 'LIKE', '%' . $query . '%') 
     ->orWhere('description', 'LIKE', '%' . $query . '%') 
     ->orWhere('address_city', 'LIKE', '%' . $query . '%') 
     ->orWhere('short_description', 'LIKE', '%' . $query . '%') 
     ->orWhere('interview', 'LIKE', '%' . $query . '%') 
     ->where('active', true)->get(); 

或者做

$foos = array_where($foos, function ($value, $key) { 
    return isset($value['active']) && (bool) $value['active']; 
});