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:
+18
-17
@@ -3,6 +3,7 @@
|
||||
namespace App\Models;
|
||||
|
||||
use App\Http\Traits\UniqueUndeletedTrait;
|
||||
use App\Models\Traits\Searchable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Log;
|
||||
use Watson\Validating\ValidatingTrait;
|
||||
@@ -45,6 +46,22 @@ class Department extends SnipeModel
|
||||
'notes',
|
||||
];
|
||||
|
||||
use Searchable;
|
||||
|
||||
/**
|
||||
* The attributes that should be included when searching the model.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $searchableAttributes = ['name', 'notes'];
|
||||
|
||||
/**
|
||||
* The relations and their attributes that should be included when searching the model.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $searchableRelations = [];
|
||||
|
||||
|
||||
public function company()
|
||||
{
|
||||
@@ -76,23 +93,7 @@ class Department extends SnipeModel
|
||||
{
|
||||
return $this->belongsTo('\App\Models\Location', 'location_id');
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 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('notes', 'LIKE', "%$search%");
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Query builder scope to order on location name
|
||||
*
|
||||
|
||||
Reference in New Issue
Block a user