1 回答

TA貢獻1804條經(jīng)驗 獲得超7個贊
這是未經(jīng)測試的,當(dāng)然可以改進,但這應(yīng)該可以滿足您的要求:
將以下方法添加到您的模型中,或者更好的是添加到由所有其他模型擴展的基本模型中:
/**
* 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();
- 1 回答
- 0 關(guān)注
- 162 瀏覽
添加回答
舉報