I write a trait in laravel named prioritiable and I add a global scope to the query to sort the query result based on priority value
The problem is the scope add the order by SQL clause to all SELECT, DELETE , UPDATE , INSERT
but I want to just to have the scope on select
so I did this
trait Prioritiable
{
protected static function bootPrioritiable(): void
{
static::retrieved(function ($model) {
$model->addGlobalScope(OrderByPriorityScope::class);
});
}
}
The problem solved for first, find , firstOrFail , findOrFail but the scope does not work for get , all , paginate, since I think these three functions do not fire the retrieved event
the A_I says use $builder->getQuery()->type == ‘select’ in the scope apply function but the type does not exists and throws error
or do something like this
public function apply(Builder $builder, Model $model)
{
$query = $builder->getQuery();
// Apply only for SELECT queries that aren't aggregates
if ($query->columns !== null && $query->aggregate === null) {
$builder->orderBy('priority');
}
}
which not work fine