我目前正在从 CakePHP 文档添加到博客示例,并创建了一个用户表以便将帖子分配给某个用户,并且我已经在我的帖子表中添加了一个 user_id 字段
我在我的帖子控制器中编写了以下函数:
public function viewuser($user_id = null){
if (!$this->Post->exists($user_id)) {
throw new NotFoundException(__('Invalid user'));
}
$options = array('conditions' => array('Post.user_id' => $user_id));
$this->set('posts', $this->Post->find('all', $options));
}
但是当我访问两者时,它会返回所有用户的所有帖子http://localhost/cake-app/posts/viewuser/1
,http://localhost/cake-app/posts/viewuser/2
而不是仅返回具有发布$user_id
值的用户的帖子。
有人可以帮我解决这个问题吗?我是 CakePHP 的新手,所以它可能是一个简单的修复。
编辑 - 生成的 SQL 如下:
1 SELECT COUNT(*) AS `count` FROM `jaredisalie`.`posts` AS `Post` WHERE `Post`.`id` = 1
2 SELECT `Post`.`id`, `Post`.`title`, `Post`.`user_id`, `Post`.`imageurl`, `Post`.`category_id`, `Post`.`summary`, `Post`.`content`, `Post`.`created`, `Post`.`modified`, `Category`.`id`, `Category`.`title`, `User`.`id`, `User`.`username`, `User`.`name`, `User`.`password`, `User`.`role`, `User`.`created`, `User`.`modified` FROM `jaredisalie`.`posts` AS `Post` LEFT JOIN `jaredisalie`.`categories` AS `Category` ON (`Post`.`category_id` = `Category`.`id`) LEFT JOIN `jaredisalie`.`users` AS `User` ON (`Post`.`user_id` = `User`.`id`) WHERE `Post`.`user_id` = 1
3 SELECT `Category`.`id`, `Category`.`title` FROM `jaredisalie`.`categories` AS `Category` WHERE 1 = 1
4 SELECT `Posts`.`id`, `Posts`.`title`, `Posts`.`user_id`, `Posts`.`imageurl`, `Posts`.`category_id`, `Posts`.`summary`, `Posts`.`content`, `Posts`.`created`, `Posts`.`modified` FROM `jaredisalie`.`posts` AS `Posts` WHERE `Posts`.`category_id` IN (1, 2, 3)
5 SELECT `Post`.`id`, `Post`.`title`, `Post`.`user_id`, `Post`.`imageurl`, `Post`.`category_id`, `Post`.`summary`, `Post`.`content`, `Post`.`created`, `Post`.`modified`, `Category`.`id`, `Category`.`title`, `User`.`id`, `User`.`username`, `User`.`name`, `User`.`password`, `User`.`role`, `User`.`created`, `User`.`modified` FROM `jaredisalie`.`posts` AS `Post` LEFT JOIN `jaredisalie`.`categories` AS `Category` ON (`Post`.`category_id` = `Category`.`id`) LEFT JOIN `jaredisalie`.`users` AS `User` ON (`Post`.`user_id` = `User`.`id`) WHERE 1 = 1 ORDER BY `Post`.`modified` desc LIMIT 20
6 SELECT COUNT(*) AS `count` FROM `jaredisalie`.`posts` AS `Post` LEFT JOIN `jaredisalie`.`categories` AS `Category` ON (`Post`.`category_id` = `Category`.`id`) LEFT JOIN `jaredisalie`.`users` AS `User` ON (`Post`.`user_id` = `User`.`id`) WHERE 1 = 1