Laravel和PHP最佳多重搜索方法

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

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
}

我想要做什么

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

问题是

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

这意味着我需要检查$text变量和$pet变量是否为空,然后执行以下查询:

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

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

是否有更快速和更优化的解决方案?


查看适用于Laravel的可搜索包 https://github.com/nicolaslopezj/searchable 您可以使用bootstrap typeahead插件,实现漂亮定制的搜索功能。 - Sapnesh Naik
@SapneshNaik,我会阅读它的,谢谢 :) - Ahmed Essam
1个回答

9

选项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();

选项 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();

1
这是一个非常好的解决方案,正是我正在寻找的。我不知道我可以在Laravel中做到这一点:D - Ahmed Essam
完美的解决方案对我来说 :) 今天正在寻找它..感谢您的答案。 - icynets

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接