cakephp 3.4- 分页 belongsToMany 关联

cakephp 3.4- Paginating belongsToMany associations

我有 3 个模型。

菜单 -> BelongsToMany -> 标签 -> BelongsToMany -> 帖子。

我得到 menu_slug 作为输入,我必须对即将发布的帖子进行分页。

我编写的查询按预期工作,但我无法根据帖子对其进行分页。

我的查询是:

$posts=$this->Menus->findByMenuSlug($slug)->contain(['Tags'=>function($query){
            return $query->contain(['Posts'=>function($qry){
                return $qry->select(['id','title','slug','short_description','created'])->where(['status'=>1,'is_deleted'=>2,'is_approved'=>1])->orderDesc('Posts.created');
            }]);
       }])->first();`

我不知道如何使用分页器实现它。请帮忙。

您好,经过长时间的搜索,我找到了解决方案。我不确定这是否是执行此操作的最佳方法,但它目前有效。如果有人有更好的解决方案请提供。

对我有用的解决方案是:

    $this->loadComponent('Paginator');

    $this->Paginator->setConfig([
        'limit'=>20
    ]);

    $menu=$this->Menus->find()->where(['menu_slug'=>$slug])->contain(['Tags'])->first();
    $tagIds=[];
    if (!empty($menu->tags)){
        foreach ($menu->tags as $tag) {
            $tagIds[]=$tag->id;
        }
    }

    $posts=[];

    if (!empty($tagIds)){
        $posts=$this->Posts->find()->contain(['Tags'=>function(Query $query)use($tagIds){
            return $query->where(['Tags.id IN'=>$tagIds]);
        }])->orderDesc('created');
        $posts=$this->paginate($posts);
    }

    $this->set(compact('menu','posts'));`