A
A
akula222019-02-08 16:19:25
Yii
akula22, 2019-02-08 16:19:25

How to make orderBy from 2 tables using AR with?

There are 2 tables, paper and paper_category
, both have a position field by which I need to sort them.
Output should be like this
CATEGORY1
-paper1
-paper2
CATEGORY2
-paper5
-paper8
I do this

$array = Paper::find()->select(['id', 'title', 'cat_id', 'position'])->asArray()
            ->with(['category' => function($query) {
                $query->orderBy(['paper_category.position' => SORT_DESC]);
            }])
            ->orderBy(['paper.position' => SORT_DESC])
            ->all();
        return ArrayHelper::map($array, 'id', 'title', 'category.title');

Sort by paper, not by category.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Timofeev, 2019-02-08
@webinar

You seem to be confusing with and joinWith. You have sent 2 requests. 1 took Paper, the second pulled category links, with 1 request for all Paper. Look in the sql logs that you received and everything will become clear.

A
akula22, 2020-04-01
@akula22

UP
needed to add one more output field

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question