kohana / orm

Kohana ORM
159 stars 108 forks source link

Creating node by has_one relation #113

Open ghost opened 9 years ago

ghost commented 9 years ago

I have the next code:

class Model_User extends Model_Auth_User 
{

    protected $_has_one = array(
        'profile' => array(
            'model' => 'User_Profile',
            'foreign_key' => 'user_id'
        )
    );

    protected $_has_many = array(
        'user_tokens' => array(
            'model' => 'User_Token',
            'foreign_key' => 'user_id',
        ),
        'roles'  => array(
            'model' => 'Role',
        'through' => 'roles_users'
        )
    );

}

So, i can create Model_User node and, for example, a few roles for user by:

public function createUser(array $userData, array $userProfileData, array $roles)
{
    // ...

    $this->values()->check()->save();
    $this->add('roles', $roles);

    // ...
}

But, how i can create the profile node? Profile is a simple model, which has user_id as primary key and other non-value data (first_name, last_name of user and etc.).

So, i tried to do this:

public function createUser(array $userData, array $userProfileData, array $roles)
{
    // ...

    $this->values()->check()->save();
    $userId = $this->id;

    $userProfileData['user_id'] = $userId;

    ORM::factory('User_Profile')->values($userProfileData)->check()->save(); // this

    $this->add('roles', $roles);

    // ...
}

But in values() method primary_key (user_id) is unsetting! So, i need use this:

ORM::factory('User_Profile')->set('user_id', $userId)->values($userProfileData)->check()->save(); 

That looks strange, i think. Need to create method as 'add()' (add() for has_many relations) for has_one relation, i think.