MilMike
MilMike

Reputation: 12831

How to get the count of joined table (HABTM)

Is there a way to get the count of items connected using HABTM? For example I have tables Users and Tags. (and another one tags_users)

user model has the following:

public $hasAndBelongsToMany = array("Tags");

I can do simply $this->User->find("all") and I get the users and connected tags from the Tags table. But instead of getting the tags I want to get the amount of the tags (count) for every user.

How to do this in cake?

Upvotes: 0

Views: 125

Answers (1)

MilMike
MilMike

Reputation: 12831

I found a simple solution: In the User Model I just specify a virtualfield:

public  $virtualFields = array(
  'tag_count' => 'SELECT count(*) FROM tags_users WHERE user_id = User.id'
  );

Upvotes: 1

Related Questions