通过循环构建函数调用

时间:2013-07-29 01:59:16

标签: php laravel laravel-4

我正在尝试为现实网站构建搜索功能。我希望能够一次搜索多个参数,类似于您在几乎任何零售网站上看到的内容。我正在我的项目上使用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 个答案:

答案 0 :(得分: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);
}

当然,您必须改进它以处理>和其他人。但我认为你明白了,对吧?

最后:

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