0

I have 3 Models.

Menus -> BelongsToMany -> Tags -> BelongsToMany -> Posts.

I am getting menu_slug as Input and I have to Paginate the Posts that are coming.

The query that I wrote is working as expected but I am not able to Paginate it according to Posts.

My query is:

$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();`

I don't have any Idea how to Implement this using Paginator. Please help.

Sainesh Mamgain
  • 754
  • 1
  • 10
  • 32

1 Answers1

0

Hi so after long search I figured out the solution. I don't know for sure if this is the best way to do this but it's working for now. If anybody has a better solution Please do provide that.

Solution that worked for me is:

    $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'));`
Sainesh Mamgain
  • 754
  • 1
  • 10
  • 32