1

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.

1 Answer 1

5

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')"));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.