首页 > 解决方案 > 查找已标记为 X 和 Y 但未标记为 Z 的文章

问题描述

假设我的文章可以有很多标签。我希望能够找到所有标记为 X 和 Y,但不是 Z 的文章。

数据库看起来像这样:

文章

标签

文章标签

现在,如果我想找到所有标记为 X 和 Y 的文章,我可以这样做:

$tags = ['X', 'Y'];
$articles = TableRegistry::get('Articles');
$articles = $articles
    ->find()
    ->innerJoinWith('Tags')
    ->where(['Tags.name IN' => $tags])
    ->group(['Articles.id'])
    ->having([$this->query()->newExpr('COUNT(DISTINCT Tags.name) = ' . count($tags))]);

或者如果我想找到所有没有被标记为 Z 的文章,我可以这样做:

// ...
$articles = $articles
    ->find()
    ->notMatching('Tags', function ($q) use ($tags) {
        return $q->where(['Tags.name IN' => $tags]);
    });

但是,如果我想查找所有标记为 X 和 Y 而不是 Z 的文章怎么办?我花了几个小时试图获得一个有效的查询,但我就是想不通。

如果我结合这两个查询,我会收到以下错误:

Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Tags.name' in 'where clause'

组合查询如下所示:

$tags = ['X', 'Y'];
$tags_not = ['Z'];
$articles = TableRegistry::get('Articles');
$articles = $articles
    ->find()
    ->innerJoinWith('Tags')
    ->where(['Tags.name IN' => $tags])
    ->group(['Articles.id'])
    ->having([$this->query()->newExpr('COUNT(DISTINCT Tags.name) = ' . count($tags))])
    ->notMatching('Tags', function ($q) use ($tags_not) {
        return $q->where(['Tags.name IN' => $tags_not]);
    });

有任何想法吗?

标签: phpcakephpcakephp-3.0

解决方案


$excluded = $this->Articles
    ->find()
    ->select('id')
    ->matching('Tags', function($q) use($tags_not) {
        return $q->where(['Tags.name IN' => $tags_not]);
})->toArray();
$excludedIds = array_column($excluded, 'id');

$articles = $this->Articles
    ->find()
    ->where(['Articles.id NOT IN' => $excludedIds])
    ->matching('Tags', function($q) use($tags) {
        return $q->where(['Tags.name IN' => $tags]);
});

推荐阅读