如何在CakePHP 3.0中复制Query :: notMatching()?

时间:2015-08-06 19:21:53

标签: php cakephp orm cakephp-3.0

我不喜欢使用cakephp 3.1 beta。我正在使用3.0版。我正在尝试查找没有特定标签的所有帖子。我怎么能这样做?

1 个答案:

答案 0 :(得分:2)

为了复制notMatching()的行为,您必须添加适当的LEFT联接,其条件与应排除的标记相匹配,另一个LEFT联接包括连接表,然后在主查询上使用条件,通过对连接表主键的IS NULL检查来排除具有匹配标记的行。

这是一个基本的例子,假设Posts belongsToMany Tags关系

$query = $Posts
    ->find()
    ->leftJoin(
        ['Tags' => 'tags'],
        ['Tags.title' => 'specificTagToExlcude']
    )
    ->leftJoin(
        ['PostsTags' => 'posts_tags'],
        'Posts.id = PostsTags.post_id AND Tags.id = PostsTags.tag_id'
    )
    ->where([
        'PostsTags.id IS NULL'
    ]);

这将创建类似于

的查询
SELECT
    Posts.id AS `Posts__id`,
    // ...
FROM
    posts Posts 
LEFT JOIN
    tags Tags 
        ON Tags.title = 'specificTagToExlcude' 
LEFT JOIN
    posts_tags PostsTags
        ON PostsTags.post_id = Posts.id 
        AND PostsTags.tag_id = Tags.id 
WHERE
    PostsTags.id IS NULL