2017-01-12 18 views
0

在數據庫中,我有「類別」和「產品」表。在「產品」表中,有一個category_ids列是一個數組,因爲該產品具有多個類別。Laravel 5 - 如何查詢DB值是否爲數組

我想要的是查詢category_ids爲1的產品。我試圖這樣做,它是有效的,但我想要一個更簡單的方法如何做。

$catId = 1; //category ID 
$allProducts = Product::all(); // get all products 
foreach ($allProducts as $product) { //loop all the products 
    if(in_array($catId, $product->category_ids)) { // check if category ID is in array of its product categories 
    $products[] = Product::find($product->id); 
    } 
} 

正如你可以在上面看到,我必須遍歷所有的產品,以檢查是否類別ID在產品類別陣列存在。

有沒有更好的方法,所以它不檢查所有的產品?

回答

0

除一行外,所有代碼都可以。

$catId = 1; //category ID 
$allProducts = Product::all(); // get all products 
foreach ($allProducts as $product) { //loop all the products 
    $cats = explode(',',$product->category_ids); 
    if(in_array($catId, $cats)) { // check if category ID is in array of its product categories 
     $products[] = Product::find($product->id); 
    } 
} 

我加了這行。我認爲一個產品的多個類別將被存儲在與逗號單場分離(雖然它不是正確的方法,你需要創建一個M2M表)

$cats = explode(',',$product->category_ids); 

所以in_array功能,第二個元素應該是數組。並且由於爆炸的輸出,$ cats是一個數組。

in_array($catId, $cats) 
+0

嗨Naveed,謝謝你的回答。但我認爲你在這裏錯過了理解:),對不起。 db中的值是數組,我已經爲category_ids列添加了屬性casting數組,因此不需要使用explode。事情是我上面的代碼是可行的,但我想知道是否有更好的方式沒有循環所有的產品。就像whereIn一樣,但它是whereIn的反向函數。 whereIn正在檢查數據庫值,如果它在數組中。我想要一個相反的功能,如果存在,我很高興。 – Wakanina

+0

啊好的,那麼我的答案是否定的。因爲in_array節省開發人員的時間,所以它很好用:) –