SQL带分隔符的子句

时间:2017-11-02 17:38:47

标签: php mysql

如何编写SQL搜索语句,其中输入是空格分隔的字符串,每个单词属于不同的列?

例如:

  

搜索输入: 2011年奥迪Q7

     

“2011”搜索年份,

     

“奥迪”搜索品牌,

     

和“Q7”搜索模型

我正在使用AJAX为我的SQL表创建一个过滤器,这是我正在使用的代码,但是不起作用:

数据库

|year|make|model|
----------------
|2017|Audi|Q7
----- ---- -----
 ... | ...| ...

PHP

public function categoryOptions() {
    $term = $this->request->input('term');
    $options = VehiclesModel::where('year', 'like', '%'.$term.'%')->where('make', 'like', '%'.$term.'%')->where('model', 'like', '%'.$term.'%')->get();
    return $options->pluck('id','year','make','model');
}

我想我需要在'%'.$term.'%'中使用分隔符,但不确定这是怎么做的。

1 个答案:

答案 0 :(得分:0)

' '拆分$ term,你将得到一个年份在[0]中的数组,在[1]中生成,在[2]中建模。 类似的东西:

public function categoryOptions() {
    $term = $this->request->input('term');
    $terms = explode(' ', $term);
    $options = VehiclesModel::where('year', 'like', '%'.$terms[0].'%')->where('make', 'like', '%'.$terms[1].'%')->where('model', 'like', '%'.$terms[2].'%')->get();
    return $options->pluck('id','year','make','model');
}