PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, February 27, 2022

[FIXED] CakePHP 3: [ManyToMany] Getting Bookmarks with MULTIPLE specific tags

 February 27, 2022     cakephp, cakephp-3.0     No comments   

Issue

I want to archive somthing quite similar to the Bookmark Tutorial here: https://book.cakephp.org/3/en/tutorials-and-examples/bookmarks/intro.html#getting-bookmarks-with-a-specific-tag

To find Bookmarks with the Tags "funny", "cat", "gifs" This query is usable in the BookmarksController:

$tags = ['funny','cat','gifs'];
$bookmarks = $this->Bookmarks->find();
  ->innerJoinWith('Tags')
  ->where(['Tags.title IN ' => $tags]);
  ->group(['Bookmarks.id']);

$this->set('result',$tags);

This returns the Bookmarks tagged with funny OR cat OR gifs.

Im trying to change this to return only Bookmarks taged with funny AND cat AND gifs.

Does anyone has a hint how to archive this?


Solution

Thanks I got it working. This is how

$current_tags = ['funny','cat','gifs']
$query = $this->Bookmarks->find()->contain(['Tags'])
            ->matching('Tags', function($query) use ($current_tags){
                return $query->where(['Tags.name IN' => $current_tags]);
            });
            $query->group('Bookmarks.id')->having([
        $this->Bookmarks->query()->newExpr('COUNT(DISTINCT Tags.name) = '.count($current_tags))
    ]);

Thanks to this answer i solved a problem i had after follwoing the comented answer above. The Problem appears when using variables for the array to search in. in this case $current_tags.

matching([...]) is using an anonymous function. anonymous functions have a new scope. This is why the variable has to be inherited using use().



Answered By - mjd
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing