LoginSignup
3
3

More than 5 years have passed since last update.

cakephp3 hasmany 関連モデルの合計及び、最新いいね順でソート

Last updated at Posted at 2018-10-07

・OjisansTable 単
・IinesTable 複 hasmany

の関係になっている。
joinして累計したい。


        $query = $this->Ojisans->find();

        $query->select(['total_result'=> $query->func()->count('Iines.id')])
        ->autoFields(true)
        ->contain('Iines')
        ->leftJoinWith('Iines')
        ->group(['Ojisans.id'])
        ->order(['total_result' => 'desc']);


これで hasmany 先の 合計のレコード数でソートできる。

最新いいね順でソートしたい


        $query = $this->Ojisans->find();

        $query->select(
            [
                'total_result'=> $query->func()->count('Iines.id'),
                'max_id' => $query->func()->max('Iines.id')//Iinesテーブルの中で最大のIDを取得
            ])
            ->autoFields(true)
            ->contain([
                'Iines' => function ($q) {
                    return $q->order(['Iines.id' => 'asc']);
                }
            ])
            ->leftJoinWith('Iines')
            ->order(['max_id' => 'desc'])
            ->group(['Ojisans.id']);




    $res = $query->all();

これで最新いいね順で取得できる。

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3