2

In my Yii2 Project I have an array for example

$array = [];    
$array [] = 8 , 3, 6

So when I print out the array is

[8,3,6]

So when I use the same in a where statement it jumbles up.

$class = ModelClass::find()->where(['array_no' => $array])->all

So when I print out class I get the output in asc order sorted.. I get the information of

  • 3 in the first
  • 6 in the second place
  • 8 in the third place.

How can i stop this from happening. I want them to return my output in the same order as array

4

1 Answer 1

4

You should use ORDER BY FIELD(), e.g. :

$models = ModelClass::find()
  ->where(['array_no' => $array])
  ->orderBy(new \yii\db\Expression('FIELD (array_no, '.implode(',', $array).')'))
  ->all();
Sign up to request clarification or add additional context in comments.

1 Comment

Yea but it throws me a undefine function call when I use yii/db/expression

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.