3

I have data on my PostgreSQL like this :

background

id | Size
1  | small
2  | medium
3  | large

art

id | name       | background_id
1  | Shine      | 1
2  | Sun        | 3
3  | Mountain   | 3

I want to get art data orderBy background by it's value from small (small, medium, large) with laravel eloquent

Art::with( [ 'background' => function( $background ) {
    $background->oderBy( DB::raw( "what is this?" ) );
} ] )->get();

How to fix it?

FIELD(type, 'S', 'M', 'L', 'XL')

is not working

2 Answers 2

6

You can use a CASE WHEN expression along with orderByRaw():

$queryOrder = "CASE WHEN Size = 'small' THEN 1 ";
$queryOrder .= "WHEN Size = 'medium' THEN 2 ";
$queryOrder .= "ELSE 3 END";
Art::with('background')
->orderByRaw($queryOrder);
->get();
Sign up to request clarification or add additional context in comments.

Comments

0

I would add an order field to the background table so ordening can be changed when a new field is added without having to change code. Then, you can use the following query:

Art::with('background')
->orderBy('background.order')
->get();

2 Comments

It's show error SQLSTATE[42P01]: Undefined table: 7 ERROR: missing FROM-clause entry for table
Have you set the $table property in your Art model?

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.