I
I
Ilya Beloborodov2018-03-13 13:42:53
Yii
Ilya Beloborodov, 2018-03-13 13:42:53

Yii2 sort by number of related materials?

There is such. Tags are selected in the place with the pages to which this tag is attached.
But I need not to select the whole list, but just count the number of attached materials + sort by this number

public function getPages()
    {
        return $this
            ->hasMany(Page::className(), ['id_page' => 'id_page'])
            ->viaTable(TagJoinPage::tableName(), ['id_tag' => 'id_tag']);
    }

    public function getDataProvider()
    {
        return new ActiveDataProvider(['query' => self::find()->joinWith(['pages'])]);
    }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Timofeev, 2018-03-13
@webinar

https://stackoverflow.com/questions/31782754/yii2-...

I
Ilya Beloborodov, 2018-03-13
@kowap

Made with SqlDataProvider

public function getDataProvider()
  {
    return new SqlDataProvider([
      'sql' => 'select `tag`.*, (select count(*) from `tag_join_page` where `tag_join_page`.`id_tag` = `tag`.`id_tag`) as `total` from `tag` order by `total` DESC',
      'pagination' => [
        'pageSize' => 50
      ]
    ]);
  }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question