Laravel 6.x 本地高级字符串搜索

我有 Laravel 6.x,需要对 mariaDB 进行高级搜索。我需要一个搜索来搜索所有包含特定字符串的列。


例子:


+----+-------+--------------+

| id | name  | lastname     |

+----+-------+--------------+

| 1  | peter | peterjackson |

+----+-------+--------------+

| 2  | petery| hans         |

+----+-------+--------------+

| 3  | hans  | han          |

+----+-------+--------------+

| 4  | petty | bun          |

+----+-------+--------------+

搜索查询:


peter: 1


peters: /


pet: 1,2,3


我已经尝试过 TNT 搜索,但它只搜索整个字符串是否相同。所以pet只会在 id=2 时触发。


TNT 搜索示例(Laravel Scout):


People::search("pet")->get()


*no records*


People::search("peter")->get()


record id 1 (id 2 not included)


Algolia 搜索不是一个选项,因为我无法将数据外包到其他数据中心。


手掌心
浏览 87回答 1
1回答

三国纷争

这是未经测试的,当然可以改进,但这应该可以满足您的要求:将以下方法添加到您的模型中,或者更好的是添加到由所有其他模型扩展的基本模型中:/** * An array containing the names of all of this model's columns * @var [] */private $_columnNames = [];/** * Get an array of info for the columns of the given connection and table * @return array */public function columnInfo(){    return DB::connection($this->connection)->select(DB::raw('SHOW FULL COLUMNS FROM '.$this->table.';'));}/** * Get an array of all the column names for this db model * @return array */public function getColumnNames(){    if (!$this->_columnNames) {        $this->_columnNames = Arr::pluck($this->columnInfo(), 'Field');    }    return $this->_columnNames;}/** * Get all records where any table column is like the given value * @param string $value * @param array  $selectColumns An array of columns to return * @return \Illuminate\Database\Query\Builder */public static function whereAnyColumnLike($value, $selectColumns){    $queryColumns = (new self)->getColumnNames();    $selectColumns = $selectColumns ?: $queryColumns;    $query = self::select($selectColumns);    foreach($queryColumns as $key => $column) {        $function = $key === 0 ? 'where' : 'orWhere';        $query->$function($column, 'LIKE', $value);    }    return $query;}然后你可以打电话SomeModel::whereAnyColumnLike('%pet%')->get();
打开App,查看更多内容
随时随地看视频慕课网APP