在获取Primary Model数据及其关联数据时,可以使用 matching
及 join
从句对关联数据进行匹配。
matching
匹配指定的关联数据,但结果集中并不包含关联数据。
INNER JOIN连接查询,可使用 distinct()
方法去除重复数据。
匹配的关联数据保存在Entity的 _matchingData
属性中。
使用 notMatching
执行相反的操作,LEFT JOIN查询,可与 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
分组查询组合使用;