嗨,我目前正在做一个项目,想知道是否有可能在cakephp中做两个find函数?例如,我正在制作一个体育新闻网站,我将新闻文章分组为头条新闻、底层新闻和头条新闻。
我想要做的是检索头条新闻,这样我就可以突出这些作为突出的故事,然后在understory下面将作为次要的故事,然后标题将是最不重要的。
这是我到目前为止所拥有的
function latestnews() {
$articles = $this->Article->find('all',
array('limit' =>3,
'order' =>
array('Article.date_created' => 'desc')));
if(isset($this->params['requested'])) {
return $articles;
}
$this->set('articles', $articles);
$articler = $this->Article->find('all',
array('Article.type' => 'topstory',
'Limit' => '1'
));
$this->set('articles', $articler);
}
但是,这似乎不起作用,它并没有限制$articles函数,而是回显表中的所有数据。
在视图中,我执行了一个标准的foreach语句来回显数据,结果抛出了一个未定义的变量错误。
我所说的是可能的吗?还是我应该创建不同的函数,然后将它们用作元素?
感谢您在此之前的任何意见!
发布于 2012-08-08 22:05:49
我没有在一个函数中使用两个find方法,而是选择简单地创建不同的函数并将它们用作元素,例如...
function premiershiptopstory() {
$pltopnews = $this->Article->find('all', array(
'conditions' => array('Article.league' => 'premiership',
'Article.type' => 'topstory')));
if(!empty($this->request->params['requested'])) {
return $pltopnews;}
$this->set('article', $pltopnews);
}
但是,在视图中,您必须请求操作,否则将抛出一个错误,要请求操作,只需使用此行代码...
<?php $pltopnews = $this->requestAction('/Articles/premiershiptopstory');
希望这对其他人有帮助!
发布于 2012-07-10 13:13:48
您可以将关联关系与其自身动态绑定。尝试以下代码:
function latestnews() {
$this->Article->bindModel(array('hasMany' => array('TopStory' => array('className' => 'Article',
'foreignKey' => false,
'conditions' => array('Article.type' => 'topstory')
),
'Highlight' .....
)));
$articles = $this->Article->find('all',
array('limit' =>3,
'order' => array('Article.date_created' => 'desc')));
if(isset($this->params['requested'])) {
return $articles;
}
$this->set('articles', $articles);
$articler = $this->Article->find('all',
array('Article.type' => 'topstory',
'Limit' => '1'
));
$this->set('articles', $articler);
}
希望它能为你工作。
发布于 2012-07-10 18:54:35
@Arun不,这似乎不起作用,我得到了这个错误,Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Article.type' in 'where clause'
我也试图把它放在一个有自己函数的元素中,然后我抛出了这个错误……
Notice (8):未定义的变量: data APP/View/Elements/Articles/topstories.ctp,第5行警告(2):为foreach() APP/View/Elements/property/topstories.ctp的第5行提供的参数无效通知(8):未定义的属性: View::$Paginator CORE/Cake/View/View.php,第806行致命错误:在第21行的/Applications/XAMPP/xamppfiles/htdocs/kickoff/app/View/Elements/Articles/topstories.ctp中的非对象上调用成员函数prev()
控制器代码如下...
function topstories() {
$this->paginate = array(
'conditions' => array('Article.type' => 'topstory'),
'limit' => 2,
'order' => array(
'date_created' => 'asc'
)
);
$data = $this->paginate('Article');
$this->set(compact('data'));
}
我发现这个错误令人困惑,好像我没有把它放在一个元素中,而是放在一个视图中,它可以完美地工作!然而,在一个不那么完美的元素中: is‘为什么会这样呢?
https://stackoverflow.com/questions/11400836
复制相似问题