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


CakePHP converts ID field to $this->id in model

CakePHP 2.6.x

我使用烘焙 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 惯例?非常欢迎对这里发生的事情进行任何解释。

调用 $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;

正如 Mark 在他的评论中建议的那样,在模型中使用 $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