O
O
Offereight2018-02-06 14:03:27
Yii
Offereight, 2018-02-06 14:03:27

How to build an SQL query in Yii2 in such a way that it would be sorted simply by the field being filled, and not by the content in it?

Good day.
How to build a query in a Yii model to check if a field in a table is filled in? Now the table stores the number of goods, you just need to find out in the query that this number is not equal to 0 and sort it so that the goods with the quantity not equal to 0 go first, and then the rest. Sorting simply by the number of products is not suitable, because in addition to this sorting, there are 2 more (by price and by one more field).

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Maxim Timofeev, 2018-02-06
@webinar

2 requests and union. We chose everything that is not 0 with one sort, we chose everything that is 0 without sorting, merged

$query1 = Product::find()->andWhere(['>','price',0])->orderBy('price');
$query2 = Product::find()->andWhere(['price'=>0]);
$query1->union($query2);
$query1->all(); // или скормили дата провайдеру

M
Maxim Fedorov, 2018-02-06
@qonand

$query->orderBy([
    new \yii\db\Expression('(`count` = 0) ASC')
])

$query is the query object you are executing, `count` is your count column

D
Dmitry Kim, 2018-02-06
@kimono

Sorting simply by the number of products is not suitable, because in addition to this sorting, there are 2 more (by price and by one more field).

So you indicate the first sorting of goods exactly by quantity, and then by price, etc. This is a question more for the SQL query itself than for Yii.
In Yii, something like this:
$products = Product::find()->where([/**/])->orderBy(['count' => SORT_DESC, 'price' => SORT_DESC, 'eshe_odno_pole' => SORT_DESC])->all();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question