1

For simplicity's sake, I have two tables: projects and tasks. A project can have many tasks, and a task belongs to a project. I've set up the database, created the associations and used cake bake to generate the models, controllers and views and all is perfect. When I look at a the index view for projects, I see a table listing all the projects as expected. What I want to do is really simple: I want a column in that table that shows a count of all the tasks assigned to that project.

The SQL query for this is trivial (returning a list of project names and a count of the tasks):

SELECT projects.name,
(SELECT COUNT(*) FROM tasks WHERE project_id = projects.id) as taskCount
FROM projects

So how do I achieve this in CakePHP? The index method in the projects controller looks like this at the moment:

function index() {
    $this->Project->recursive = 0;
    $this->set('projects', $this->paginate());
}

1 Answer 1

1

You can use the virtualFields or counterCache, but it is another way.

Sign up to request clarification or add additional context in comments.

1 Comment

Added this to the project model: var $virtualFields = array ( 'taskcount' => 'SELECT COUNT(*) FROM tasks WHERE project_id = Project.id'); and all is good!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.