2011-05-16 38 views
0

所有,

我想知道我怎么会从视图中传递一个$变量,例如,当前的文章ID($文章[“文章'] ['id'])发送到articles_controller.php函数中的find('all')调用。

function getRelated($id = null){ 
$relatedarticles = $this->Article->find(
        'all', 
        array(
         'fields' => array(
         'Article.title' 
         ), 
         'limit' => 4, 
         'order' => 'Article.id ASC', 
         'recursive' => 1, 
         'conditions' => array(
         'Article.category_id =' => $id 
         ) 
         ) 
        ); 

if (!empty($this->params['requested'])) { 
    return $relatedarticles; 
} else { 
    $this->set(compact('relatedarticles')); 
} 
} 

然后从视图中,我会叫这样的事情。我似乎无法得到这个工作...什么是最好的方式来做到这一点?

<div id="articles_view_related"> 
Related News 
<?php 
    $currentid = $articles['Article']['id']; 
    $relatedarticles = $this->requestAction('/articles/getRelated/id:$currentid'); 
    //debug($relatedarticles); 
?> 
<ul> 
    <?php 
     foreach($relatedarticles as $relatedarticle){ 
    ?> 
    <li> 
     <?php 
      echo $relatedarticle['Article']['title']; 
     ?> 
    </li> 
    <?php 
     } 
    ?> 
</ul> 

</div> 

谢谢你的所有帮助

回答

2

我努力工作,你为什么以这种方式完成这个任务,但这里是你的答案仍然:

$relatedarticles = $this->requestAction('/articles/getRelated/'.$currentid); 

你不需要id:$currendId,因为你的动作中的参数,在URL中的/ controller/action /之后的任何内容将被声明为$id in getRelated($id = null);例如:/articles/getRelated/23$id将等于23.


应该做什么,被宣告getRelated()方法在模型,然后使用控制器动作来获取内容,并把它传递给视图。 如:

$relatedArticles = $this->Article->getRelated($article['Article']['id']); 
$this->set(compact('relatedArticles)); 

对于要重复,坚持在您的模型:)

+0

非常感谢您的快速回复数据操作。我是CakePHP和MVC的新手,很多时候我试图弄清楚什么去了哪里。如果我暗示正确,我应该在我的文章模型中创建一个getRelated($ id = null)函数,就像我上面那样,但没有if语句。然后在我的控制器中使用您的建议代码(我在这里创建相同的功能?)。在我看来,我应该删除requestAction调用。我很感谢你对此的帮助...... – 2011-05-16 13:47:34

+0

是的,我认为你已经掌握了它,如果你想在其他任何行动中包含相关文章(我认为这是你的总体目标),只需拨打'$ this- >文章 - > getRelated()'在你的其他动作中。 – Dunhamzzz 2011-05-16 13:51:23

+0

太棒了...你是对的。我也想在其他操作中使用getRelated。感谢您的教训......我会尝试您的建议,并在稍后回复。 – 2011-05-16 13:57:16

相关问题