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
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.