CakePHP - 在模型中设置默认字段值 [英] CakePHP - Set Default Field Values in the Model
本文介绍了CakePHP - 在模型中设置默认字段值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何为模型中的字段设置默认值?
How do you set a default value for a field in a model?
我已按照建议尝试使用 _schema 的方法,但未使用默认值.
I have tried the method using _schema as suggested, but the default value is not being used.
public $_schema = array(
'newsletter' => array(
'default' => 1
),
);
推荐答案
您可以在数据库中设置值并在模式中对其进行管理,例如:
You can set the value in database and get it managed in schema, e.g.:
public $items = array(
'id' => array('type' => 'integer', 'null' => false, 'default' => null, 'length' => 10, 'unsigned' => false, 'key' => 'primary'),
'quantity' => array('type' => 'decimal', 'null' => false, 'default' => '1.00', 'length' => '12,2', 'unsigned' => false),
// ^^^^^^^^^^^^^^^^^^^
'indexes' => array(
'PRIMARY' => array('column' => 'id', 'unique' => 1),
),
'tableParameters' => array('charset' => 'utf8', 'collate' => 'utf8_spanish_ci', 'engine' => 'InnoDB')
);
这个默认值可以稍后通过模型的schema
属性在模型或控制器中读取:
This default value can be read later in model or controller though the model's schema
property:
// Controller example
$itemSchema = $this->Item->schema();
$defaultQuantity = $itemSchema['quantity']['default'];
// ... or:
$quantityInfo = $this->Item->schema('quantity');
$defaultQuantity = $quantityInfo['default'];
在最近的 PHP 版本中,它可以是单行的:
In recent PHP versions it can be a one-liner:
$defaultQuantity = $this->Item->schema('quantity')['default'];
这适用于带有 MySQL 适配器的 Cake/2.5(不知道其他场景).
This works in Cake/2.5 with MySQL adapter (no idea of other scenarios).
这篇关于CakePHP - 在模型中设置默认字段值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文