cakePHP中的view函数不能使用$ id以外的变量

时间:2012-04-14 23:01:30

标签: php cakephp cakephp-2.0

我正试图在我的'文本'控制器中为视图函数传递$ id以外的变量:

public function view($postid = NULL) {
        $this->Text->postid = $postid;
        $this->set('text', $this->Text->read());
    }

我做错了什么?

4 个答案:

答案 0 :(得分:1)

你在那做什么? 你可以使用只读主键 - 通常是

$this->Text->id = $postid;

答案 1 :(得分:0)

$primaryKey模型的Text属性是否设为'postid'?如果没有,那么$this->Text->read()就不会像你想要的那样工作。在app/Model/Text.php中,将其添加到您的班级:

public $primaryKey = 'postid';

如果您不想更改主键,也可以执行以下操作(但您可能应该更改主键):

$text = $this->Text->find('first', array(
    'conditions' => array('postid' => $postid),
));
$this->set('text', $text);

另外,尝试在您的视图中添加这样的内容,以查看变量中的实际内容:

<pre><?php var_dump($text); ?></pre>

这可能会让您更好地了解正在发生的事情。

最后,这里有一些相关文档:

答案 2 :(得分:0)

您可以将视图功能自定义为:

public function view($name = NULL) {
    $record = $this->Text->findByName($name);        
    $this->set('text', $record);
}

此处name是一个字符串。 name字段应存在于数据库中。 您可以通过debugging.debug($ record)查看$ record的内容。

答案 3 :(得分:0)

想出来:

public function view($postid = NULL) { 
$post = $this->Text->find('first', array('conditions' => 
                                          array('Text.postid'=>$postid))); 
$this->set('text', $post); 
}