【发布时间】:2017-05-17 23:43:44
【问题描述】:
我有一个博客模型,但我怀疑我没有正确编写代码以充分利用 CakePHP 的 MVC 结构。
这里有一些来自我的 Posts 控制器的 sn-ps。
public function view() {
$posts = $this->Posts->find('all')->contain([
'Comments' => ['Users'],
'Users'
]);
$this->set(compact('posts'));
}
public function index() {
$post = $this->Posts->find('all')->contain([
'Users'
])->limit(20);
$this->set(compact('post'));
}
这是来自index.ctp 模板的sn-p
foreach ( $posts as $post ) {
<div class="post">
<h1 class="title>
<?= h($post->title) ?>
<small><?php echo $post->getCommentCount(); ?> comments</small>
</h1>
<div class="body">
<?= h($post->body) ?>
</div>
</div>
}
在我的帖子实体中,我有以下功能
public function getCommentCount(){
$count = 0;
foreach ($this->comments as $comment){
if ( $comment->isPublished() ) {
$count += 1;
}
}
return $count;
}
我的问题是我需要从index.ctp 调用getCommentCount 函数,其中$posts 对象没有comment 子级(该函数使用)。
我是否误解了实体函数的编码方式?我应该从实体查询数据库,而不是访问该对象的 expected 变量(有时不存在)?我应该采取另一种方法吗?
【问题讨论】:
-
添加你的 index.ctp sn-p 显示 getCommentCount() 的调用
-
@RayannNayran 完成!
-
你得到了什么结果?
-
@RayannNayran
Invalid arguments supplied for foreach在实体类中。这是有道理的,因为在这种情况下,post变量中没有提供任何comments。
标签: cakephp model-view-controller