开发者

Adding a custom query to the model

开发者 https://www.devze.com 2023-03-16 07:49 出处:网络
For simplicity\'s sake, I have two tables: projects and tasks. A project can have many tasks, and a task belongs to a project.

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());
}


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号