CakePHP-matching&joinを使用して関連データを照合

5180 ワード

Primary Modelデータおよびその関連データを取得する場合、matchingおよびjoinを使用して関連データを文からマッチングすることができる.
matching
指定した関連データと一致しますが、結果セットには関連データは含まれません.INNER JOIN接続クエリーは、distinct()メソッドで重複データを除去できます.一致する関連データは、Entityの_matchingData属性に保存されます.notMatchingを使用して反対の操作を実行し、LEFTJOINクエリはmatchingと組み合わせて使用できます.
//Authors HasMany Articles
$query = $this->Authors->find();
$query->matching('Articles', function($q) {
    return $q->where(['Articles.created >=' => new DateTime('-10 days')]);
});

//Deep associations
$query = $this->Products
                ->find()
                ->matching('Shops.Cities.Countries', function($q) {
                        return $q->where(['Countries.name' => 'China']);
                    }
                )
                ->distinct(); //  

//Using passed variables
$username = 'jack';
$query = $this->Articles->find()->matching('Comments.Users', function($q) use ($username) {
    return $q->where(['username' => $username]);
});

innerJoinWith matchingと同じ役割を果たしますが、結果セットに追加されたフィールドおよび_matchingDataの属性はありません.
leftJoinWith
Don’t load any columns from the specified associations into the result set
//  Primary Model           
$query = $articlesTable->find();
$articles = $query
            //->select($articlesTable)
            ->select([
                'comments_count' => $query->func()->count('Comments.id')
            ])
            ->leftJoinWith('Comments')
            ->group(['Articles.id'])
            ->having(['comments_count >' => 10]) //      
            ->enableAutoFields(true) //   select($articlesTable)
            ->all();

//Deep associations
$query = $authorsTable
            ->find()
            ->select(['total_articles' => $query->func()->count('Articles.id')])
            ->leftJoinWith('Articles.Tags', function($q) {
                return $q->where(['Tags.name' => 'CakePHP']);
            })
            ->group(['Authors.id'])
            ->enableAutoFields(true);
wherehavingの違い-whereはデータテーブルのフィールドから直接フィルタリングされます.-havingは、前のクエリーフィールドからフィルタされます.-havingは、しばしばgroupパケットクエリと組み合わせて使用される.