Laravel 和 php 最好的多重搜索方法

Ahm*_*sam 3 php mysql laravel eloquent

我有一个控制器,可以从搜索表单中获取四个输入。

SearchController.php 代码

public function results(Request $request) {
    $text           = $request -> text;
    $pet            = $request -> pet;
    $category       = $request -> category;
    $city           = $request -> city;
    $searchArray    = [];
    if(empty($text) && empty($pet) && empty($category) && empty($city)) {
        Session::flash('danger', "You didn't select any search any search.");
        return redirect() -> back();
    }

    //SEARCH CODE HERE
}
Run Code Online (Sandbox Code Playgroud)

我想做什么

我正在尝试在我的数据库中搜索 4 列

问题是

我还需要在一个查询中搜索 4 列。

这意味着我需要检查$text变量是否不为空并且$pet变量不为空然后我必须执行以下查询:

if(!empty($text) && !empty($pet))
            $result = Post::where('text', 'like', '%'.$text.'%') -> where('text', $pet) -> get();
Run Code Online (Sandbox Code Playgroud)

这种方法可以正常工作,但我将有多个 if 语句来检查所有可能性。

有更快更好的解决方案吗?

Ale*_*nin 6

选项1

手动构建逻辑。在许多情况下,这是最好的方法。一个例子:

$result = Post::query();

if (!empty($text)) {
    $result = $result->where('text', 'like', '%'.$text.'%');
}

if (!empty($pet)) {
    $result = $result->where('pet', $pet);
}

if (!empty($category)) {
    $result = $result->where('category', $category);
}

if (!empty($city)) {
    $result = $result->where('city', 'like', '%'.$city.'%');
}

$result = $result->get();
Run Code Online (Sandbox Code Playgroud)

选项 2

使用条件从句。例子:

Post::when($text, function ($q) use ($text) {
        return $q->where('text', 'like', '%'.$text.'%');
    })
    ->when($pet, function ($q) use ($pet) {
        return $q->where('pet', $pet);
    })
    ->when($category, function ($q) use ($category) {
        return $q->where('category', $category);
    })
    ->when($city, function ($q) use ($city) {
        return $q->where('city', 'like', '%'.$city.'%');
    })
    ->get();
Run Code Online (Sandbox Code Playgroud)