CakePHP: Number of Users with Posts or Pages tagged with a given Tag
-
27-04-2021 - |
Question
We have the following relationship for our data:
Users
- Have and belong to many Pages
- Have and belong to many Posts
Pages
- Have and belong to many Users
- Have and belong to many Tags
Posts
- Have and belong to many Users
- Have and belong to many Tags
Tags
- Have and belong to many Pages
- Have and belong to many Posts
Here is our question: Is there a way to get just a count of how many unique Users have ever created either a Page or Post that has been tagged with a given Tag?
In our Tag model:
function getSupportingUserCount($tag_id)
{
$user_count = $this->find(?);
return $user_count;
}
Solution
You can just avoid joins that may be slow if you've got many rows. So first get the tagid, then search for that id via the User model associations.
$tag = $this->Tag->find('first', array('conditions' => array('Tag.name' => 'blahblah'), 'recursive' => -1);
$tag_id = $tag['Tag']['id'];
$this->User->find('count', array('conditions' => "OR" => array (
array('Page.tag_id' => $tag_id,
'Post.tag_id' => $tag_id )
));
(untested code so there may be typos)
(aside: are you sure each Post has many users? usually a post has only 1 author)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow