2014-11-22 87 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