Kohana 3-将模型与关系归属关系保存到数据库

时间:2018-11-29 14:59:09

标签: kohana-3 kohana-orm

我有一个简单的问题,但在文档和论坛中都找不到答案。

简而言之-我在Kohana 3中有2个模型-Task和TaskType。 我想以一种方式创建Task模型,然后可以引用$ task-> task_type_id-> name字段。

不幸的是,当您将记录插入数据库时​​,我得到了答案: “一般错误:1364字段'task_type_id'没有默认值”

当我将task_type_id字段添加为普通字段(在$ _table_columns中)时,则无法通过$ task-> task_type_id-> name引用视图中的TaskType对象。

我不知道如何配置模型以保存与数据库的关系并能够在视图中引用它。

请帮助。

我的模型代码:

class Model_Task extends ORM
{
    protected $_table_name  = 'task';

    protected $_table_columns = array(
        'id'=>array('data_type'=>'int','is_nullable'=>false),
        'date' => array('data_type'=>'date','is_nullable'=>
        'description'=>array('data_type'=>'varchar','is_nullable'=>true)
    );

    protected $_belongs_to = array(
        'task_type_id' => array(
            'model'       => 'TaskType',
            'foreign_key' => 'id'
        )
    );
}

class Model_TaskType extends ORM
{
    protected $_table_name  = 'task_type';

    protected $_table_columns = array(
        'id'=>array('data_type'=>'int','is_nullable'=>false),
        'name' => array('data_type'=>'string','is_nullable'=>false)
    );
}

1 个答案:

答案 0 :(得分:0)

可能应该是:

class Model_Task extends ORM
{
    protected $_table_name  = 'task';

    protected $_table_columns = array(
        'id'=>array('data_type'=>'int','is_nullable'=>false),
        'date' => array('data_type'=>'date','is_nullable'=>
        'description'=>array('data_type'=>'varchar','is_nullable'=>true),
        'task_type_id' => array('data_type'=>'int','is_nullable'=>false),
    );

    protected $_belongs_to = array(
        'task_type' => array(
            'model'       => 'TaskType',
            'foreign_key' => 'id'
        )
    );
}

class Model_TaskType extends ORM
{
    protected $_table_name  = 'task_type';

    protected $_table_columns = array(
        'id'=>array('data_type'=>'int','is_nullable'=>false),
        'name' => array('data_type'=>'string','is_nullable'=>false)
    );
}

并添加$task->add('task_type', $task_type);