Automatically add table prefixes when building multi-column search string

This commit is contained in:
Marcus Moore 2023-05-23 15:58:58 -07:00
parent 6300909fee
commit 0a3d46824e
No known key found for this signature in database
3 changed files with 14 additions and 13 deletions

View file

@ -948,8 +948,8 @@ class Asset extends Depreciable
->orWhere('assets_users.last_name', 'LIKE', '%'.$term.'%')
->orWhere('assets_users.username', 'LIKE', '%'.$term.'%')
->orWhereMultipleColumns([
DB::getTablePrefix() . 'assets_users.first_name',
DB::getTablePrefix() . 'assets_users.last_name',
'assets_users.first_name',
'assets_users.last_name',
], $term);
}
@ -1346,8 +1346,8 @@ class Asset extends Depreciable
$query->where('assets_users.first_name', 'LIKE', '%'.$search.'%')
->orWhere('assets_users.last_name', 'LIKE', '%'.$search.'%')
->orWhereMultipleColumns([
DB::getTablePrefix() . 'assets_users.first_name',
DB::getTablePrefix() . 'assets_users.last_name',
'assets_users.first_name',
'assets_users.last_name',
], $search)
->orWhere('assets_users.username', 'LIKE', '%'.$search.'%')
->orWhere('assets_locations.name', 'LIKE', '%'.$search.'%')

View file

@ -167,8 +167,8 @@ trait Searchable
if($relation == 'user') {
$query->orWhereRaw(
$this->buildMultipleColumnSearch([
DB::getTablePrefix() . 'users.first_name',
DB::getTablePrefix() . 'users.last_name',
'users.first_name',
'users.last_name',
]),
["%{$term}%"]
);
@ -273,14 +273,16 @@ trait Searchable
*/
private function buildMultipleColumnSearch(array $columns): string
{
$mappedColumns = collect($columns)->map(fn($column) => DB::getTablePrefix() . $column)->toArray();
$driver = config('database.connections.' . config('database.default') . '.driver');
if ($driver === 'sqlite') {
return implode("||' '||", $columns) . ' LIKE ?';
return implode("||' '||", $mappedColumns) . ' LIKE ?';
}
// Default to MySQL's concatenation method
return 'CONCAT(' . implode('," ",', $columns) . ') LIKE ?';
return 'CONCAT(' . implode('," ",', $mappedColumns) . ') LIKE ?';
}
/**

View file

@ -647,8 +647,8 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo
return $query->where('first_name', 'LIKE', '%' . $search . '%')
->orWhere('last_name', 'LIKE', '%' . $search . '%')
->orWhereMultipleColumns([
DB::getTablePrefix() . 'users.first_name',
DB::getTablePrefix() . 'users.last_name',
'users.first_name',
'users.last_name',
], $search);
}
@ -660,11 +660,10 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo
* @return \Illuminate\Database\Eloquent\Builder
*/
public function advancedTextSearch(Builder $query, array $terms) {
foreach($terms as $term) {
$query->orWhereMultipleColumns([
DB::getTablePrefix() . 'users.first_name',
DB::getTablePrefix() . 'users.last_name',
'users.first_name',
'users.last_name',
], $term);
}