亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

PHP
手掌心 2023-10-22 22:03:28
我有 Laravel 6.x,需要對 mariaDB 進行高級搜索。我需要一個搜索來搜索所有包含特定字符串的列。例子:+----+-------+--------------+| id | name  | lastname     |+----+-------+--------------+| 1  | peter | peterjackson |+----+-------+--------------+| 2  | petery| hans         |+----+-------+--------------+| 3  | hans  | han          |+----+-------+--------------+| 4  | petty | bun          |+----+-------+--------------+搜索查詢:peter: 1peters: /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 搜索不是一個選項,因為我無法將數據外包到其他數據中心。
查看完整描述

1 回答

?
三國紛爭

TA貢獻1804條經驗 獲得超7個贊

這是未經測試的,當然可以改進,但這應該可以滿足您的要求:


將以下方法添加到您的模型中,或者更好的是添加到由所有其他模型擴展的基本模型中:


/**

 * 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();


查看完整回答
反對 回復 2023-10-22
  • 1 回答
  • 0 關注
  • 166 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號