Refactoring: A nicer and easier syntax for searching models (#5841)

* Adds the ability to search by dates

Adding extra „where“-conditions to the „TextSearch“ queries, allowing the users to search by dates

* Adds missing dates to $dates in models

* Removes duplicated „where“ conditions

* Adds the Searchable trait to models, defining the searchable attributes and relations

* Removes the old text search methods

* Adds back additional conditions to the search

These conditions could not be modeled in the „attributes“ or „relations“, so we include them here

* Removes unnecessary check for the deleted_at attribute

* Fixes typo in comments

* suppresses errors from Codacy

We can safely ignore the error codacy is throwing here, since this method is a standin/noop for models who need to implement more advanced searches
This commit is contained in:
Till Deeke
2018-07-16 23:13:07 +02:00
committed by snipe
parent 240e642fe9
commit baa3be728d
23 changed files with 679 additions and 539 deletions
+19 -33
View File
@@ -4,6 +4,7 @@ namespace App\Models;
use App\Http\Traits\UniqueUndeletedTrait;
use App\Models\Asset;
use App\Models\SnipeModel;
use App\Models\Traits\Searchable;
use App\Models\User;
use App\Presenters\Presentable;
use Illuminate\Database\Eloquent\Model;
@@ -60,6 +61,24 @@ class Location extends SnipeModel
];
protected $hidden = ['user_id'];
use Searchable;
/**
* The attributes that should be included when searching the model.
*
* @var array
*/
protected $searchableAttributes = ['name', 'address', 'city', 'state', 'zip', 'created_at'];
/**
* The relations and their attributes that should be included when searching the model.
*
* @var array
*/
protected $searchableRelations = [
'parent' => ['name']
];
public function users()
{
return $this->hasMany('\App\Models\User', 'location_id');
@@ -171,39 +190,6 @@ class Location extends SnipeModel
return $location_options;
}
/**
* Query builder scope to search on text
*
* @param Illuminate\Database\Query\Builder $query Query builder instance
* @param text $search Search term
*
* @return Illuminate\Database\Query\Builder Modified query builder
*/
public function scopeTextsearch($query, $search)
{
return $query->where('name', 'LIKE', "%$search%")
->orWhere('address', 'LIKE', "%$search%")
->orWhere('city', 'LIKE', "%$search%")
->orWhere('state', 'LIKE', "%$search%")
->orWhere('zip', 'LIKE', "%$search%")
// This doesn't actually work - need to use a table alias maybe?
->orWhere(function ($query) use ($search) {
$query->whereHas('parent', function ($query) use ($search) {
$query->where(function ($query) use ($search) {
$query->where('name', 'LIKE', '%'.$search.'%');
});
})
// Ugly, ugly code because Laravel sucks at self-joins
->orWhere(function ($query) use ($search) {
$query->whereRaw("parent_id IN (select id from ".DB::getTablePrefix()."locations where name LIKE '%".$search."%') ");
});
});
}
/**
* Query builder scope to order on parent
*