Laravel中数据库的自定义查询

时间:2016-01-07 15:38:33

标签: php laravel

首先,我想知道在Laravel中这是否可行?

我有这段代码:

$master_array = $_POST['master_search_array'];

$count = count($master_array);
$master_string = '';

for($i=0; $i<$count; $i++) {
    if($master_array[$i] == "Dining"){
        $master_string .= "where('dining', 'dining')";
    }
    if($master_array[$i] == "Party"){
        $master_string .= "where('party','party')";
    }
    ....ETC you get the point
}

$tours = DB::table('tours')->$master_string->get();

return $tours;

所以最后我应该得到这样的东西:

$tours = DB::table('tours')->where('dining', 'dining)->where('party','party')->get();

我如何在laravel中执行此操作,无论我将其作为$master_string还是{{$master_string}}传递,都会给我一个错误。

2 个答案:

答案 0 :(得分:2)

不需要主字符串。只需使用查询构建器如何使用它......

    $master_array = $_POST['master_search_array'];

    $count = count($master_array);
    $query = DB::table('tours');

    for($i=0; $i<$count; $i++) {
        if($master_array[$i] == "Dining"){
            $query->where('dining', 'dining');
        }
        if($master_array[$i] == "Party"){
            $query->where('party', 'party');
        }
    }

    $tours = $query->get();

    return $tours;

答案 1 :(得分:0)

使用能够在整个过程中向查询添加轮廓。

DB::table('tour')->where(function($query) use ($master_array)
{
    foreach($master_array as $k => $v) {

        if($v == "Dining"){
            $query->where('dining','dining');
        }
        if($v == "Party"){
            $query->where('party','party');
        }
    }
})
->get();