我使用两个查找语句...第一个获取文章,第二个获取与本文相关的评论...我在使用我的代码时看到此错误
Content:
Notice (8): Undefined index: Article [APP\views\articles\view.ctp, line 27]
Created
Notice (8): Undefined index: Article [APP\views\articles\view.ctp, line 31]
Notice (8): Undefined index: Article [APP\views\articles\view.ctp, line 73]
articles_controller.php
function view($id=null) {
$article = $this->Article->find('all', array(
'conditions' => array(
'Article.id' => $id,
'Article.status' => 1
)
));
$comment = $this->Article->Comment->find('all',
array('conditions' =>
array('Comment.article_id' => $id, 'Comment.status' => 1)));
$this->set(compact('article','comment'));
if(!empty($article)){
// increment the number of items the dvd was viewed
$this->Article->save(array(
'Article' => array(
'id' => $id,
'views' => ($article['Article']['views'] + 1)
)
));
}
articles / view.ctp
<!-- to show article title,image,content,date -->
<div class="formats view">
<h2>Title: <?php echo $article['Article']['title']; ?></h2>
<dl>
<dt>Image:</dt>
<dd> <?php
echo $html->image($h,array('height'=>'250px', 'width'=>'280px')); ?>
</dd>
<dt>Content:</dt>
<dd><?php echo strip_tags($article['Article']['content']) ; ?></dd>
<dt>Created</dt>
<dd><?php echo substr($article['Article']['created'], 0, 15); ?></dd>
<!-- to show comments related with articles -->
<?php if(!empty($article['Comment'])): ?>
<div class="related">
<h3>Comments For this Article</h3>
<table>
<thead>
</thead>
<tbody>
<?php foreach($comment as $comments): ?>
<tr>
<tr>
<th>Name,date</th>
<td><?php echo ' '.$comments['Comment']['name'].' '.substr($comments['Comment']['created'], 0, 15); ?> </td>
</tr>
<tr>
<th>title</th>
<td><?php echo $comments ['Comment']['title']; ?></td>
</tr>
<tr>
<th>content</th>
<td><?php echo $comments['Comment']['content']; ?></td>
</tr>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php endif; ?>
此数据库表
CREATE TABLE IF NOT EXISTS `articles` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL,
`content` text NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
`views` int(11) NOT NULL,
`section_id` int(11) NOT NULL,
`status` tinyint(4) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=47 ;
答案 0 :(得分:0)
尝试更改您的第一个发现:
$article = $this->Article->Comment->find(
对此:
$article = $this->Article->find(...
(注意第二个中缺少“评论”)
另外 - 你真的没有理由需要编写2个单独的查询 - 这就是CakePHP可以通过Containable Behavior
轻松处理的问题NEXT FIX (在回答的上半部分做出更改后):
在$ article变量上执行print_r。我假设你会看到它应该是:
$article[0]['Article']
而不是
$article['Article']
答案 1 :(得分:-1)
嘿而不是以下:
<?php echo $article['Article']['title']; ?>
试
<?php echo $article['title']; ?>
我不确定为什么会这样,但在其他场合它对我有用......
另外在评论的foreach声明中,我注意到你有
<?php foreach($comment as $comments){ ?>
我认为不会正确显示您的评论。你应该
<?php foreach($comments as $comment){ ?>
在你的控制器中,使用
$comments = $this->Article->Comment->find('all', ...
我正在创建一个类似的应用程序,至少我是如何处理所有内容的。
如果您需要,我会回复或发送电子邮件给您我的文章控制器,评论控制器和相应的观点供您审核。
谢谢,