2011-05-16 31 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

相關問題