【问题标题】:Kohana 3 - Save model to DB with relation belongs_toKohana 3 - 将模型保存到数据库中,关系为 belongs_to
【发布时间】:2018-11-29 14:59:09
【问题描述】:

我有一个简单的问题,但我在任何地方都找不到答案——无论是在文档中还是在这个论坛中。

简而言之 - 我在 Kohana 3 中有 2 个模型 - 任务和任务类型。 我想以这样的方式创建一个任务模型,然后我可以引用字段 $ 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)
    );
}

【问题讨论】:

标签: kohana-3 kohana-orm


【解决方案1】:

应该是这样的:

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);添加

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多