1

我有一个 MySQL 表,其中包含一个 tinyint(1) 类型的“状态”列。(实际上这是一个布尔列,但据我所知 MySQL 不支持这种类型并自动将其转换为 tinyint(1)。)

如果我在此表上执行 ORM::factory('Model', $id) 并检查“状态”,我会得到:a) NULL,如果没有 $id b) 或(取决于存储在此表中的值)场地)

我希望能够将这三种不同的可能性用作 3 种不同的状态选项,因此执行严格的比较 - 但由于 b) 的数据类型 STRING,这是不可能的。

我试图设置

protected $_table_columns = array(
      'user_id' => array(
            'data_type' => 'integer'            
            ),
        'status' => array(
            'data_type' => 'boolean',
            'default' => FALSE,
        ),
    );

但这也不起作用(根据我目前发现的只有键很重要)。

所以我的问题是:我真的必须自己将值转换为布尔值,还是有可能为 Kohana 完成的自动转换指定数据类型?

谢谢!

4

1 回答 1

1

我发现 Kohanas 关于如何定义缺少的列的文档,我在这里和那里收集了一些东西

'type'        => 'int',  // Data type - these seem to represent PHP types, (string,int,boolean,etc.)
'default'     => 1,      // Default value

编写自己的自动生成规则相当容易,以下函数为 Kohana ORM 添加了一些额外的东西:

/**
 * Extra stuff
 * 'is_nullable' => TRUE,   // Column is nullable
 * 'max_length'  => 128,    // Maximum column length
 * 'min_length'  => 8,      // Minimum value length
 */
public function rules()
{
    // Return rules array when already set
    if ( ! empty($this->_rules))
    {
        return $this->_rules;
    }

    // Create default rules for each field
    foreach ($this->_table_columns as $name => $properties)
    {
        // Skip the primary key
        if ($name == $this->_primary_key)
        {
            continue;
        }

        // When field is a created/updated column
        // Note: this is some internal stuff we always use
        if (in_array($name, $this->_created_updated_columns))
        {
            $this->_rules[$name][] = array('digit');
        }

        // When field is of type int
        if (Arr::get($properties, 'type') == 'int' AND ! in_array($name, $this->_created_updated_columns))
        {
            $this->_rules[$name][] = array('digit');
        }

        // When field is of type string
        if (Arr::get($properties, 'type') == 'string')
        {
            $this->_rules[$name][] = array('min_length', array(':value', 1));
            $this->_rules[$name][] = array('max_length', array(':value', Arr::get($properties, 'character_maximum_length', 255)));
         }

         // When field is of type binary
         if (Arr::get($properties, 'type') == 'binary')
         {
             $this->_rules[$name][] = array('regex', array(':value', '/[01]/'));
         }

         // Add not empty rule when not nullable
         if (Arr::get($properties, 'is_nullable', FALSE) === FALSE)
         {
             $this->_rules[$name][] = array('not_empty');
         }
     }

     // Return the rules array
     return $this->_rules;
}
于 2014-01-02T09:58:49.797 回答