0

这是我在 newsses/index.ctp 中的链接

$this->Html->link(__("Read more >>", TRUE), array('action'=>'view', $newss['Newsse']['title']));

这是我在 newsses_controller.php 中的视图代码:

function view($title = NULL){
    $this->set('title_for_layout', __('News & Event', true));

    if (!$id) {
        $this->Session->setFlash(__('Invalid News.', true), 'default', array('class' => 'error')); 
        $this->redirect(array('action'=>'index'));
    }
    $this->set('newsse', $this->Newsse->read(NULL,$title));
    $this->set('newsses', $this->Newsse->find('all'));
}

但它没有显示任何内容,我想制作如下路线:“newsses/view/2”到“newsses/view/title_of_news”

请帮我....

4

2 回答 2

0

为此,您需要在模型中创建一个新方法,该方法将按新闻标题显示结果。这时候你使用 $this->Newsse->read(NULL,$title))。您在读取方法中使用 $title,而此读取方法在模型中搜索新闻 id。因此,您只需要在模型类中创建一个新方法,例如 readByTitle($title){ 在此处编写查询以按标题获取新闻}。并在您的控制器中使用此方法。$this->Newsse->readByTitle(NULL,$title))

于 2011-05-03T07:20:39.300 回答
0

您正在使用Model::read()方法方法,该方法将id您要访问的模型表中的行的第二个参数作为第二个参数。在这种情况下最好使用 find 。您无需在模型或控制器中构建新方法,只需编辑当前view方法即可。

# in newsses_controller.php:
 function view($title = null) {
     $this->set('title_for_layout', __('News & Event', true));

     if (!$id) {
        $this->Session->setFlash(__('Invalid News.', true), 'default', array('class' => 'error')); 
        $this->redirect(array('action'=>'index'));
    }

    $this->set('newsse', $this->Newsse->find('first', array(
        'conditions' => array('Newsse.title' => $title)
    ));
    $this->set('newsses', $this->Newsse->find('all'));
}

或者,您可以制作一种更加混合的形式,其中在给出数字标题时仍然可以按 id 查看(这假设您从来没有标题仅由数字字符组成的新闻项目,例如“12345”)。

# in newsses_controller.php:
 function view($title = null) {
     $this->set('title_for_layout', __('News & Event', true));

     if (!$id) {
        $this->Session->setFlash(__('Invalid News.', true), 'default', array('class' => 'error')); 
        $this->redirect(array('action'=>'index'));
    } else if (is_numeric($title)) {
        $this->set('newsse', $this->Newsse->read(NULL, $title));
    } else {
        $this->set('newsse', $this->Newsse->find('first', array(
            'conditions' => array('Newsse.title' => $title)
        ));
    }

    $this->set('newsses', $this->Newsse->find('all'));
}

最后,您还可以find用(更短的)自定义方法替换我示例中的方法(有关此内容的更多信息,findBy请参阅文档)。

$this->Newsse->findByTitle($title);
于 2011-05-03T08:38:51.763 回答