php Laravel Eloquent 的 Where 和 If 语句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25442595/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 17:50:20  来源:igfitidea点击:

Where and If Statements Laravel Eloquent

phplaraveleloquent

提问by Brent

I have built a multi filter search for my website but I cant seem to find any documentation on multiple if statements inside of where for my search.

我已经为我的网站构建了一个多过滤器搜索,但我似乎无法在我的搜索位置中找到有关多个 if 语句的任何文档。

Returns Lots of Results

返回大量结果

$data = Scrapper::paginate(15);

Returns none.. need it to be this way to have where statements with IF see bellow.

返回 none .. 需要这样才能使用 IF 的 where 语句见波纹管。

$database = new Scrapper;
$database->get();

Example of what I want to do..

我想做的例子..

    $database = new Scrapper;
    if (isset($_GET['cat-id'])) {
        $database->where('cat_id', '=', $_GET['cat-id']);
    }
    if (isset($_GET['band'])) {
        $database->where('price', 'BETWEEN', $high, 'AND', $low);
    }
    if (isset($_GET['search'])) {
        $database->where('title', 'LIKE', '%'.$search.'%');
    }
    $database->get();

回答by JofryHS

Very similar to this: Method Chaining based on condition

与此非常相似:基于条件的方法链

You are not storing each query chains.

您没有存储每个查询链。

$query = Scrapper::query();

if (Input::has('cat-id')) {
    $query = $query->where('cat_id', '=', Input::get('cat-id'));
}
if (Input::has('band')) {
    $query = $query->whereBetween('price', [$high, $low]);
}
if (Input::has('search')) {
    $query = $query->where('title', 'LIKE', '%' . Input::get($search) .'%');
}

// Get the results
// After this call, it is now an Eloquent model
$scrapper = $query->get();

var_dump($scrapper);

回答by fsasvari

Old question but new logic :)

老问题,但新逻辑:)

You can use Eloquent when()conditional method:

您可以使用 Eloquent when()条件方法:

Scrapper::query()
    ->when(Input::has('cat-id'), function ($query) {
        return $query->where('cat_id', Input::get('cat-id'));
    })
    ->when(Input::has('band'), function ($query) use ($hight, $low) {
        return $query->whereBetween('price', [$high, $low]);
    })
    ->when(Input::has('search'), function ($query) {
        return $query->where('title', 'LIKE', '%' . Input::get('search') .'%');
    })
    ->get();

More information at https://laravel.com/docs/5.5/queries#conditional-clauses

更多信息请访问https://laravel.com/docs/5.5/queries#conditional-clauses