cakePHP 3.0嵌套关联

xurqigkl  于 2022-11-11  发布在  PHP
关注(0)|答案(1)|浏览(132)

我有ArticleLists,其中hasMany ArticleListPosts,其中belongsTo Contents
我只想检索与我的以下条件相关的条目,即只有ArticleLists,具有ArticleListPosts,其Contents%search%条件匹配。这样做很好,除了它检索所有ArticleListPosts,即使有一个Contents符合%search%条件,但我只需要具有相关ContentsArticleListPosts,而不是所有的ArticleListPosts
我的疑问如下:

$query = $this->ArticleLists
    ->find()
    ->contain([
        'ArticleListPosts',
        'ArticleListPosts.Contents'
    ])
    ->innerJoinWith('ArticleListPosts')
    ->innerJoinWith('ArticleListPosts.Contents')
    ->where([
        'ArticleLists.site' => $site,
        'ArticleLists.culture' => $culture,
        'ArticleLists.language' => $language,
        'OR' => [
            ['Contents.slug LIKE' => "%$search%"],
            ['Contents.title LIKE' => "%$search%"]
        ],
    ])
    ->order([
        "ArticleLists.slug" => "ASC",
        "Contents.slug" => "ASC"
    ]);
sshcrbum

sshcrbum1#

使用hasMany,ORM生成了2个查询,所以它不会限制结果。我使用匹配来解决这个问题,并对每个关联分别应用过滤器,如@ndm所建议的。这将生成一个带有2个内连接的查询。

$query = $this->ArticleLists
                ->find()
                ->matching('ArticleListPosts', function ($q) use ($site, $culture, $language) {
                    return $q->where([
                        'ArticleLists.site' => $site,
                    'ArticleLists.culture' => $culture,
                    'ArticleLists.language' => $language,
                    ]);
                })
                ->matching('ArticleListPosts.Contents', function ($q) use ($search) {
                    return $q->where([
                        'OR' => [
                            ['Contents.slug LIKE' => "%$search%"],
                            ['Contents.title LIKE' => "%$search%"]
                        ]
                    ]);
                })

                ->order(["ArticleLists.slug" => "ASC", "Contents.slug" => "ASC"]);

相关问题