在我的模型中创建任意属性

时间:2012-10-03 16:04:00

标签: cakephp model

这是我的模特:

class Persona extends AppModel {

    // This is just some arbitrary property I need to populate in the controller.
    public $TipoPersona = ''; 
}

这是我的Controller中的Action函数:

public function details($id = null) {

    // Just a typical load by id.
    $this->Persona->id = $id;
    $this->set('persona', $this->Persona->read()); 

    // Can I do something like?
    $this->Persona->TipoPersona = "Mafa Woogly";
}

如何在“模型”中设置$TipoPersona属性?我的意图是在View中使用该属性,如:

<tr>
    <th>Tipo de Persona:</th>
    <td><?php echo h($persona->TipoPersona); ?></td> // Or similar?
</tr>

有什么建议吗?

这有效,但感觉不稳定而且没有强烈打字。

public function details($id = null) {
    $this->Persona->id = $id;
    $this->set('persona', $this->Persona->read());
    $this->set('tipoPersona', "Mafa woogly");
}

<tr>
    <th>Tipo de Persona:</th>
    <td><?php echo h($tipoPersona); ?></td>
</tr>

3 个答案:

答案 0 :(得分:1)

方法read()返回一个数组,您无法获取此对象的属性TipoPersona

我建议你在这个表中添加一个字段来指定人的类型,而不是使用read()的结果,如:

<?php echo $persona['Persona']['tipo_persona']; ?>

答案 1 :(得分:0)

您可以使用Model :: afterFind()回调将其添加到结果数组中。

您确定这不应该是模型中的常规字段吗?

答案 2 :(得分:0)

尝试使用set:

直接添加它
$this->set('tipoPersona', $this->Persona->TipoPersona);

它的属性与模型中的其他人一样。与设置$ this-&gt; Persona-&gt; id的方式相同,上面几行:)