views:

52

answers:

1

Hi,

I'm trying to join tables to get a count on a field but am having trouble figuring out how to do it. here are my tables:

tags
id     INT
tag    VARCHAR

project_tags
id         INT
project_id INT
tag_id     INT

projects
id     INT
...

I want show in my view something like this:

[tags.tag] x 23
[tags.tag] x 12
...

Now I'm no SQL expert but I think what I'd be aiming for in SQL would be performing count on tag_id where tag_id = tags.id grouped by tag_id. I think.

I'm just now so sure how to do this in a cake controller.

Can someone help?

+1  A: 

Perhaps send this query to the database:

 SELECT t.tag, COUNT(*) AS NumOccurrances
 FROM project_tags pt 
 INNER JOIN tags t ON t.id = pt.tag_id
 GROUP BY  t.tag
 ORDER BY 2 DESC  --sorting by count.

In your controller, execute ad-hoc SQL:

$results = $this->Tag->query("select ...");

More on CakePHP querying a database. Perhaps roll this up into a stored procedure in MySQL, and call from your Cake controller.

$results = $this->query("CALL MyStoredProc");
p.campbell
thanks p.campbell, I'm getting an error though. my code looks like this: $this->set('tags', $this->query('SELECT t.tag, COUNT(*) AS NumOccurrances FROM project_tags pt INNER JOIN tags t ON t.id = pt.tag_id GROUP BY t.tag ORDER BY 2 DESC'));But i'm getting an error: Call to undefined method PagesController::query() I think its because it's a method of Model. But there is no model for projects_tags so not sure what to do here
iamjonesy
@Jonesy: Try replacing `$this->query` with `$this->Tag->query`, as you noticed, query is a method of Model, not Controller class. If you have a Tag model, use that, it should work.
dr Hannibal Lecter
@dr : thanks for the tip. From those articles, it seemed to suggest that `$this->query();` was recommended for ad-hoc, but perhaps you've got it.
p.campbell
Thanks! also, I did $this->Projects->query() and everthing works alright. so it can be any old model?
iamjonesy
@Jonesy: indeed, substitute the table name there, and off you go!
p.campbell