2014-11-22 78 views
2

我:Laravel凡對象不工作

public function fetchProducts($filters = array()) { 
    print_r($filters); 
    $Product = new Product; 
    if (array_key_exists('search', $filters)) 
     $Product->where('name', 'LIKE', '%'.$filters['search'].'%'); 
    if (array_key_exists('type', $filters)) 
     $Product->where('type_id', 1); 
    if (array_key_exists('brand', $filters)) 
     $Product->where('brand_id', $filters['brand']); 

    $Product->get(); 
    return $Product; 
} 

但無論來自哪個過濾器,它返回的所有產品,似乎不顧一切。

我在做什麼錯?

+0

你用雄辯的ORM? – Ronser 2014-11-22 10:31:28

+0

@羅塞爾是的,我是。 – imperium2335 2014-11-22 10:31:57

回答

0

現在您打電話給Product模型的實例。你想要做的就是在查詢生成器實例上調用它。你做到這一點,首先調用query()

$Product = Product::query(); 

if (array_key_exists('search', $filters)) 
    $Product->where('name', 'LIKE', '%'.$filters['search'].'%'); 
if (array_key_exists('type', $filters)) 
    $Product->where('type_id', 1); 
if (array_key_exists('brand', $filters)) 
    $Product->where('brand_id', $filters['brand']); 

$Product->get(); 
+0

這給了我錯誤:語法錯誤,意外的'查詢'(T_STRING),期望變量(T_VARIABLE)或'$' – imperium2335 2014-11-22 10:34:28

+0

Ooops顯然不需要'new',因爲我們正在調用靜態方法 – lukasgeiter 2014-11-22 10:35:19

+0

Thanks that worked ,但現在我的分頁不起作用:調用未定義的方法Illuminate \ Database \ Eloquent \ Collection :: paginate() – imperium2335 2014-11-22 10:35:41

3

可以用更改

public function fetchProducts($filters = array()) { 
print_r($filters); 

$Product_query = Product::select('//values'); // i have mostly used like this 
if (array_key_exists('search', $filters)) 
    $Product_query ->where('name', 'LIKE', '%'.$filters['search'].'%'); 
if (array_key_exists('type', $filters)) 
    $Product_query ->where('type_id', 1); 
if (array_key_exists('brand', $filters)) 
    $Product_query ->where('brand_id', $filters['brand']); 

$Product = $Product_query ->get(); 
    //or 
$Product = $Product_query ->paginate(); //can also pass the paginate value like paginate($perPage) 
return $Product; 
} 

評論...

+2

好方法+1 – imperium2335 2014-11-22 10:38:54