我刚刚按照教程开始cakepp我可以在我的帖子控制器中抓取帖子表,并将其喷到我的index.ctp 上
在我的帖子控制器视图中,我还想列出发布文章的用户名。我的post表有一个user_id,所以我需要将它与我的user表匹配,并将其传递给
class PostsController extends AppController {
public function index() {
//passes values to the view
$this->set('posts', $this->Post->find('all'));
//is "Post" a post method? or is it the name of the table? i'm unsure of the syntax
$this->set('users', $this->Users->find('all')); //this does not work
}
}
感谢您对这个基本问题的帮助
您必须使用"递归"
$this->Post->find('all', array(
'recursive' => 2,
// ...
));
当然,您首先需要将模型链接在一起
我假设您已经设置了belongsTo关联(PostbelongsToUser)和/或hasMany关联(UserhasManyPost)。如果是这样的话,cake将自动带来相关的模型(除非您在模型上设置$recursive=-1)。因此,您可以访问与视图中的每个帖子相关的用户:posts[i]['User']您也可以在视图中使用它来查看视图变量:
debug($this->viewVars)
如果你不这样做,就把这个放在你的Post模型上:
public $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id',
)
);
确保正确加载模型(如果您想在PostsController中加载用户模型)。所以只需在类控制器中添加此属性。
public $uses = array('Post','User');
将模型连接在一起。您需要在Post模型中添加关联。
public $belongsTo = array(
'User'=>array(
'className'=> 'User',
'foreignKey'=>'user_id'
)
);
如果你想从数据库中检索数据,你必须设置递归性,有两种方法第一个:
$posts = $this->Post->find('all',array('recursive'=>2));
// or
$this->Post->recursive = 2;
$posts = $this->Post->find('all');
第二个:使用可传染行为在AppModel中将递归性设置为-1,并包括行为
public $recursive = -1;
public $actsAs = array('Containable');
所以简单地说,你可以用任何其他链接的模型重新发布帖子,比如
$posts = $this->Post->find('all',array(
'contain'=>array('User'),
// ...
)));