Reputation: 1306
In my Laravel application, a shirt has many sizes:
public function sizes()
{
return $this->hasMany(\App\Size::class, 'size_id');
}
A size has an attribute called name
that can be SM, MD, LG, XL, XXL, etc.
I would like to append a sortBy()
to the eloquent relationship, so that sizes always appear in order from SM up to XXL.
Is it possible to write a sort based on string values? I've only ever written them based on whether one value was greater than another, but that obviously doesn't apply here.
Upvotes: 1
Views: 439
Reputation: 5811
results can be sorted by strings using a case
:
public function sizes(){
return $this->hasMany(\App\Size::class, 'size_id')->orderByRaw(DB::raw("
CASE name WHEN 'SM' THEN 1
WHEN 'MD' THEN 2
WHEN 'LG' THEN 4
WHEN 'XL' THEN 5
WHEN 'XXL' THEN 6
ELSE 7 END ASC"));
}
There are shorter options but they aren't available for every database implementation:
Mysql
The find_in_set
for mysql would look like this:
return $this->hasMany(\App\Size::class, 'size_id')->orderByRaw(DB::raw("find_in_set(name,'SM','MD','LG','XL', 'XXL')"));
MariaDB
return $this->hasMany(\App\Size::class, 'size_id')->orderByRaw(DB::raw("find_in_set(name,'SM,MD,LG,XL,XXL')"));
Upvotes: 5