【发布时间】:2010-10-23 18:55:06
【问题描述】:
我正在尝试获取与我当前的post 相关的所有commments,我这样做如下:
$this->Post->Comment->find('all', array('conditions' => array('post_id' => $id)));
但在我看来,这有点不舒服。为什么我应该给post_id?我想要与当前Post 相关的Comment 不是很明显吗?
【问题讨论】:
我正在尝试获取与我当前的post 相关的所有commments,我这样做如下:
$this->Post->Comment->find('all', array('conditions' => array('post_id' => $id)));
但在我看来,这有点不舒服。为什么我应该给post_id?我想要与当前Post 相关的Comment 不是很明显吗?
【问题讨论】:
$this->Post->Comment->...指模型结构。 $this 表示这个类的这个实例,而不是当前记录。
所以$this 是 PostsController,$this->Post 是 Post 模型,$this->Post->Comment 是 Comment 模型。这些都不是指特定的记录。
$this->Post->id 只有在之前的查询(在此方法中)检索到明确的结果时才会设置,并且我只依赖于在$this->MyModel->save($data) 之后立即设置它,否则我会明确设置它,例如:
$this->MyModel->id = $id;
就我个人而言,我会这样做,并在一个语句中检索所有必需的关联数据:
$this->Post->contain(array('Comment')); // If you're using containable, which I recommend. Otherwise just omit this line.
$this->Post->read(null,$id);
现在您将在一个数组中拥有 Post 及其关联的 cmets,如下所示:
Array
(
[Post] => Array
(
[id] => 121
[title] => Blah Blah an More Blah
[text] => When the bar is four deep and the frontline is in witch's hats what can be done?
[created] => 2010-10-23 10:31:01
)
[Comment] => Array
(
[0] => Array
(
[id] => 123
[user_id] => 121
[title] => Alex
[body] => They only need visit the bar once in the entire night.
[created] => 010-10-23 10:31:01
)
[1] => Array
(
[id] => 124
[user_id] => 121
[title] => Ben
[body] => Thanks, Alex, I hadn't thought of that.
[created] => 010-10-23 10:41:01
)
)
)
...你会像这样进入 cmets:
$comments = $this->data['Comment'];
关于该帖子的所有您想要的(您可以在contain() 调用中进行微调)都会在一个方便的数据包中返回。顺便说一句,如果您还没有阅读 Containable 行为,请务必阅读。越早开始使用,生活就会越轻松。
【讨论】:
如果您不指定条件($this->Post->Comment->find('all');),您将获得所有 cmets 及其相关记录。
建议在条件中指定型号名称:$this->Post->Comment->find('all', array('conditions' => array('Comment.post_id' => $id)));。通过这种方式,您将获得特定帖子的 cmets 以及所有关联(与 cmets 相关的)数据。
如果您不喜欢 'conditions' 数组,您需要明确指定 id,如 Leo 提到的(来自 Post 控制器):
$this->Post->id = $id;
$this->Post->read();
这样您将获得帖子以及与之关联的所有数据。
请注意,在第一种方法中,您检索与 cmets 关联的所有数据,而在第二种方法中 - 所有与帖子关联的数据。
【讨论】:
debug($data); 在视图中。 cmets 应位于$data['Comment'];。