2013-07-29 104 views
0

我正在尝试为现实网站构建搜索功能。我希望能够一次搜索多个参数,类似于您几乎在任何零售网站上看到的内容。我在我的项目中使用了Laravel,并且希望能够使用查询生成器,以便可以使用它构建的分页。通过循环构建函数调用

如果我尝试类似:

$listing = DB::select('select * from listings where city = 'Chicago'); 

我不能分页的结果。

另一种方法是做到这一点:

$listing = DB::table('listings')->where('city', 'Chicago')->get(); 

但问题是,我不知道一个用户可能有多少参数输入搜索。所以,我将如何建立一个函数调用可能看起来像:

$listing = DB::table('listings')->where('city', 'Chicago')->where('askingPrice', '>', 50000)->where('bedrooms', '>', 3)->get(); 

回答

1

比方说,你有这样的参数:

<?php 
$parameters = array(
    'one' => 'a', 
    'two' => 'b', 
    'three' => 'c' 
); 

创建对象:

<?php 
$listing = DB::table('listings'); 

,然后循环:

<?php 
foreach ($parameters as $key => $value) { 
    $listing = $listing->where($key, $value); 
} 

cour你必须改进它以处理>等。但我认为你明白了吧?

最后:

<?php 
$listing = $listing->get(); 
+0

这是否查询数据库多次,或者只有当你使用get()? – vikingsfan19

+0

仅当使用'get()'时。 'where()'返回'\ Illuminate \ Database \ Query \ Builder'不执行查询。 – TheFrost

+0

当我这样做时,我无法分页。我认为我可以用'$ listing-> get();'替换'$ listing-> paginate(20);' – vikingsfan19