Search code examples
phpfuelphpfuelphp-orm

FuelPHP ORM one to one relation is not saving?


I'm trying to execute the following, the array contains some data that should be saved to the timeline table and the rest to the calendar table. However only the defaults or null data gets saved to the calendar while the timeline is updated correctly, the calendar_id field is set to 0.

/controller.php

$model = \Timeline\Model_Timeline::forge();
$model->calendar = \Timeline\Model_Calendar::forge();
$model->set($item);
$model->save();

/model/timeline.php

namespace Timeline;

class Model_Timeline extends \Orm\Model
{
    protected static $_properties = array(
        'id',
        'user_id' => array(
            'data_type' => 'int',
            'form' => array('type' => false),
        ),
        'calendar_id' => array(
            'data_type' => 'int',
            'form' => array('type' => false),
            'default' => '0'
        ),
        'created_at' => array(
            'data_type' => 'int',
            'form' => array('type' => false),
            'default' => '0'
        ),
        'updated_at' => array(
            'data_type' => 'int',
            'form' => array('type' => false),
            'default' => '0'
        )
    );

    protected static $_has_one = array(
        'calendar' => array(
            'key_from' => 'calendar_id',
            'model_to' => 'Timeline\\Model_Calendar',
            'key_to' => 'id',
            'cascade_save' => true,
            'cascade_delete' => true,
        )
    );

/model/calendar.php

namespace Timeline;

class Model_Calendar extends \Orm\Model
{
    protected static $_properties = array(
        'id',
        'start',
        'end',
        'recurrenceRule',
        'recurrenceException',
        'isAllDay',
        'created_at',           
        'updated_at'
    );

    protected static $_belongs_to = array(
        'calendar' => array(
            'key_from' => 'id',
            'model_to' => 'Timeline\\Model_Timeline',
            'key_to' => 'calendar_id',
            'cascade_save' => true,
            'cascade_delete' => true,
        )
    );
}

Solution

  • Assuming these variables are arrays of columns => values, you can directly do

    $model = \Timeline\Model_Timeline::forge($timeline_properties);
    $model->calendar = \Timeline\Model_Calendar::forge($calendar_properties);
    $model->save();