How to use JOIN in Yii2 Active Record for relational model?

后端 未结 1 1981
太阳男子
太阳男子 2021-01-12 07:01

I have 2 tables called Books and Reviews. Books table has a one-to-many relationship with Reviews.

I want to search books and sort them by Reviews.

For exam

1条回答
  •  醉梦人生
    2021-01-12 07:59

    Use joinWith. For more see

    For example, for your case code like that:

    Books::find()
        ->joinWith(['reviews' => function ($q) {
            $q->select(['COUNT(*) as cnt']);
        }])
        ->orderBy(['cnt' => 'DESC'])
        ->all();
    

    EDIT: I find better solution.

    Books::find()
        ->joinWith(['reviews'])
        ->select(['*', 'COUNT(reviews.*) as cnt'])
        ->groupBy('RELATION_FIELD(Example: reviews.book_id)')
        ->orderBy(['cnt' => 'DESC'])
        ->all();
    

    0 讨论(0)
提交回复
热议问题