MongoDB中的默认字段和值,使用cakePHP
我正在使用MongoDB中的默认字段和值,使用cakePHP,php,cakephp,mongodb,model,default-value,Php,Cakephp,Mongodb,Model,Default Value,我正在使用CakePHP2.1和mongodb 2.03构建一个应用程序,我正在使用 我需要设置一些将添加到模型中的默认值,我就是这样做的 <?php class DynamicFormResponse extends AppModel{ public $useDbConfig = 'mongodb'; public $useTable = 'dynamicFormsResponse'; public $primaryKey = '_id'; publi
CakePHP2.1
和mongodb 2.03
构建一个应用程序,我正在使用
我需要设置一些将添加到模型中的默认值,我就是这样做的
<?php
class DynamicFormResponse extends AppModel{
public $useDbConfig = 'mongodb';
public $useTable = 'dynamicFormsResponse';
public $primaryKey = '_id';
public $validate=array();
public $mongoschema = array(
'created' => array('type' => 'datetime'),
'modified' => array('type' => 'datetime'),
'escalation'=>array(
'type'=>"integrer",
"default"=>0
),
"status"=>array(
"type"=>"string",
"default"=>"pending"
),
);
public function setSchema($schema) {
$this->_schema=$schema;
}
public function getSchema(){
return $this->_schema;
}
}
这不是mongoDB的问题,但无论如何,我建议您将您的用户数据与beforeSave()中的默认值合并
我们在每个模型中声明默认值,如下所示:
public $defaultValues = array(
'report' => 't',
'reportinterval' => '7',
'type' => '0'
);
并将其合并到beforeSave()中:
这其实不是mongoDB的问题,但无论如何,我建议您将用户数据与beforeSave()中的默认值合并
我们在每个模型中声明默认值,如下所示:
public $defaultValues = array(
'report' => 't',
'reportinterval' => '7',
'type' => '0'
);
并将其合并到beforeSave()中:
遗憾的是,这不起作用,默认值被添加到$this->data
中,但它们不会出现在数据库中。这是从我当前项目中复制粘贴出来的,效果非常好。您是否在使用无模式行为?如果没有,可能您忘记了在模式中定义字段。是的,我使用的是Mongodb,所以我想我使用的是无模式行为。我是说这个。你需要激活它,否则你必须声明你的字段。我已经激活了这个行为,但仍然没有什么区别,你能详细说明一下吗?遗憾的是,这不起作用,默认值被添加到$this->data
中,但它们不会出现在数据库中。这是我当前项目的复制粘贴,效果很好。您是否在使用无模式行为?如果没有,可能您忘记了在模式中定义字段。是的,我使用的是Mongodb,所以我想我使用的是无模式行为。我是说这个。你需要激活它,否则你必须声明你的字段。我已经激活了这个行为,但仍然没有什么区别,你能详细说明一下吗?
public $defaultValues = array(
'report' => 't',
'reportinterval' => '7',
'type' => '0'
);
/**
* Extends beforeSave() to add default values
*
* @param array $options
* @return bool
*/
public function beforeSave($options = array()) {
// Add default values if not set already
foreach ($this->defaultValues as $fieldName => $defaultValue) {
if (empty($this->data[$this->alias][$fieldName]))
$this->data[$this->alias][$fieldName] = $defaultValue;
}
return parent::beforeSave($options);
}