C
C
Crash2018-03-28 15:11:14
Yii
Crash, 2018-03-28 15:11:14

Is it possible to preserve the order specified in the intermediate table when selecting through relationships?

There are 2 tables - patterns and actions, interconnected through an intermediate table (many-to-many). I need to get all the actions of a pattern, in a specific order. I do it through connections.
In the pattern model, I did this:

public function getPatternMoves()
    {
        return $this->hasMany(PatternMove::className(), ['pattern_id' => 'id'])
            ->orderBy('order_num ASC');
    }
    
    public function getMoves()
    {
        return $this->hasMany(Move::className(), ['id' => 'move_id'])
            ->via('patternMoves');
    }

As you might guess, the order_num column, which is responsible for the output order, is in the intermediate table. The problem is that sorting doesn't work. At the request level, the following happens:
Here it is:
SELECT * FROM `pattern_moves` WHERE `pattern_id`=1 ORDER BY `order_num`

But here it is already lost: How can I overcome this using ActiveRecord in Yii2? Or will you have to do without connections?
SELECT * FROM `moves` WHERE `id` IN (4, 2, 3)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Timofeev, 2018-03-28
@Bandicoot

Do it via join, otherwise it won't work

D
davidnum95, 2018-03-28
@davidnum95

public function getMoves()
    {
        return $this->hasMany(Move::className(), ['id' => 'move_id'])
            ->viaTable('pattern_moves',   ['pattern_id' => 'id'])->orderBy('order_num ASC');
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question