CakePHP将ID字段转换为模型中的$ this-> id

时间:2015-01-28 23:42:55

标签: php cakephp cakephp-2.0

CakePHP 2.6.x

我使用bake CLI创建模型,创建了名为ID的字段。注意它是大写的。

所以在我的模型中,我期望引用这样的属性:$this->ID,因为属性名称通常与字段名称匹配(根据我的经验)。它肯定在控制器中以这种方式工作。例如,我有很多控制器代码,如下所示:

$this->SomeModel->findById( $model['SomeModel']['ID'] );

然而,这个没有在模型中工作。经过大量的讨论和实验,我终于发现模型属性名为id(注意小写)。

//in SomeModel.php
var_dump( $this->ID ); //NULL
var_dump( $this->id ); 33

这是预期的行为吗? 所有模型属性是否转换为小写?如果是这样,为什么控制器不同?我是否以某种方式违抗CakePHP大会?对这里发生的事情的任何解释都是最受欢迎的。

1 个答案:

答案 0 :(得分:0)

当您致电$this->id时,您正在访问模型的id属性,而不是数据库中字段的值。

来自消息来源;

<?php
/**
 * Value of the primary key ID of the record that this model is currently pointing to.
 * Automatically set after database insertions.
 *
 * @var mixed
 */
public $id = false;

正如马克在评论中建议的那样,在模型中使用$this->primaryKey = 'ID'来达到预期效果,然后你可以在2.6中做这样的事情:

<?php
$this->id = 33;     // Set the active record
$this->field('ID'); // Returns 33 (If you really want to use uppercase)
$this->id;          // Returns 33
$this->read();      // Returns all of record 33