fuel / orm

Fuel PHP Framework - Fuel v1.x ORM
http://fuelphp.com/docs/packages/orm/intro.html
151 stars 95 forks source link

Orm\Model::from_array() don't work properly. #417

Closed ysshir closed 6 years ago

ysshir commented 6 years ago

Orm\Model::from_array() don't work properly, if relation model contains array field.

class Model_A extends \Orm\Model {

    protected static $_primary_key = ['id'];
    protected static $_properties  = [
        'id',
        'bid',
        'data' => [
            'default'    => array(),
            'data_type'  => 'json',
            'json_assoc' => true,
        ],
    ];

    protected static $_observers = [
        'Orm\Observer_Typing' => [
            'events' => array('before_save', 'after_save', 'after_load'),
        ],
    ];

    protected static $_has_one = [
        'b' => [
            'key_from'     => 'bid',
            'model_to'     => 'Model_B',
            'key_to'       => 'id',
            'cascade_save' => true,
        ],
    ];
}
class Model_B extends \Orm\Model {

    protected static $_primary_key = ['id'];
    protected static $_properties  = [
        'id',
        'data' => [
            'default'    => array(),
            'data_type'  => 'json',
            'json_assoc' => true,
        ],
    ];

    protected static $_observers = [
        'Orm\Observer_Typing' => [
            'events' => array('before_save', 'after_save', 'after_load'),
        ],
    ];
}
namespace Fuel\Tasks;

class Test {
    public function run() {
        \Package::load('Orm');

        $a = \Model_A::forge([
            'id'   => 1,
            'bid'  => 1,
            'data' => '{ "a": "a", "b": "b" }',
        ], false);

        $a->b = \Model_B::forge([
            'id'   => 1,
            'data' => '{ "a": "a", "b": "b" }',
        ], false);

        $b_is_new = $a->b->is_new();

        $array = $a->to_array();
        $a->from_array($array);

        assert($b_is_new === $a->b->is_new());
    }
}

I think orm/classes/model.php line 2079 should be if (array_key_exists($id, $this->_data_relations[$property]::properties())) instead of if (array_key_exists($id, $this->_data_relations[$property]))

Thanks.

WanWizard commented 6 years ago

Absolutely brillant find! Thanks!

WanWizard commented 6 years ago

Reverted.