Kohana 3 - Save model to DB with relation belongs_to

66 Views Asked by At

I have a simple problem but I can not find an answer anywhere - neither in the documentation nor in this forum.

In short - I have 2 models in Kohana 3 - Task and TaskType. I would like to create a Task model in such a way that I can then refer to the field $ task-> task_type_id-> name.

Unfortunately, when you insert a record into the database, I get the answer: "General error: 1364 Field 'task_type_id' does not have a default value"

When I add the task_type_id field as a normal field (in $ _table_columns), then I can not refer to the TaskType object in the view via $ task-> task_type_id-> name.

I do not know how to configure the model to save the relation to the database and be able to refer to it in the view.

Please help.

My models code:

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

There are 1 best solutions below

0
bato3 On

Probably it should be:

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)
    );
}

and adding by $task->add('task_type', $task_type);