CakePHP-matching&joinを使用して関連データを照合
5180 ワード
Primary Modelデータおよびその関連データを取得する場合、
matching
指定した関連データと一致しますが、結果セットには関連データは含まれません.INNER JOIN接続クエリーは、
innerJoinWith
leftJoinWith
Don’t load any columns from the specified associations into the result set
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);
where
とhaving
の違い-where
はデータテーブルのフィールドから直接フィルタリングされます.-having
は、前のクエリーフィールドからフィルタされます.-having
は、しばしばgroup
パケットクエリと組み合わせて使用される.