Adapt multiple column search based on database driver

This commit is contained in:
Marcus Moore 2023-05-18 12:54:00 -07:00
parent 869d195b35
commit 9cb0decf35
No known key found for this signature in database
2 changed files with 30 additions and 1 deletions

View file

@ -646,11 +646,27 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo
{ {
$query = $query->where('first_name', 'LIKE', '%'.$search.'%') $query = $query->where('first_name', 'LIKE', '%'.$search.'%')
->orWhere('last_name', 'LIKE', '%'.$search.'%') ->orWhere('last_name', 'LIKE', '%'.$search.'%')
->orWhereRaw('CONCAT('.DB::getTablePrefix().'users.first_name," ",'.DB::getTablePrefix().'users.last_name) LIKE ?', ["%{$search}%"]); ->orWhereRaw(
$this->buildMultipleColumnSearch([
DB::getTablePrefix() . 'users.first_name',
DB::getTablePrefix() . 'users.last_name',
]),
["%{$search}%"]
);
return $query; return $query;
} }
public function buildMultipleColumnSearch(array $columns): string
{
$driver = config('database.connections.' . config('database.default') . '.driver');
if ($driver === 'sqlite') {
return implode(" || ' ' || ", $columns) . ' LIKE ?';
}
return 'CONCAT(' . implode('," ",', $columns) . ') LIKE ?';
}
/** /**
* Run additional, advanced searches. * Run additional, advanced searches.

View file

@ -30,6 +30,19 @@ class UsersForSelectListTest extends TestCase
->assertJson(fn(AssertableJson $json) => $json->has('results', 3)->etc()); ->assertJson(fn(AssertableJson $json) => $json->has('results', 3)->etc());
} }
public function testUsersCanBeSearchedByFirstAndLastName()
{
User::factory()->create(['first_name' => 'Luke', 'last_name' => 'Skywalker']);
Passport::actingAs(User::factory()->create());
$response = $this->getJson(route('api.users.selectlist', ['search' => 'luke sky']))->assertOk();
$results = collect($response->json('results'));
$this->assertEquals(1, $results->count());
$this->assertTrue($results->pluck('text')->contains(fn($text) => str_contains($text, 'Luke')));
}
public function testUsersScopedToCompanyWhenMultipleFullCompanySupportEnabled() public function testUsersScopedToCompanyWhenMultipleFullCompanySupportEnabled()
{ {
$this->settings->enableMultipleFullCompanySupport(); $this->settings->enableMultipleFullCompanySupport();