Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

ORM -storing related records

I am experiencing a strange behavior on v 1.3.4 :

class UserProfile
{
    // .... code
    public function initialize()
    {
        $this->hasOne('user_profile_user_id', 'App\Core\Models\User', 'id', array(
            'alias' => 'user',
            'reusable' => true
        ));
    }   
    // ... code
}

class User
{
    // .... code
    public function initialize()
    {
        $this->hasOne('user_profile_id', 'App\Core\Models\UserProfile', 'id', array(
            'alias' => 'profile',
            'reusable' => true
        ));
    }   
    // ... code
}

Creating a record :

        $security = $this->getDI()->get('security');

        $user = new User();
        $user->setUserFirstName($data['user_first_name']);
        $user->setUserLastName($data['user_last_name']);
        $user->setUserEmail($data['user_email']);
        $user->setUserPassword($security->hash($data['user_password']));
        $user->setUserIsActive($data['user_is_active']);

        $user_group_id = $this->findFirstGroupByName($user_group_name)->getId();
        $user->setUserGroupId($user_group_id);

        $profile = new UserProfile();
        $profile->setUserProfileLocation($data['user_profile_location']);
        $profile->setUserProfileBirthday($data['user_profile_birthday']);

        $user->profile = $profile;

        $user->create();

Will return me: userprofileuser_id is required

Anyone had similar problems ?

Try to use save instead of create

save is just a shortcut to both create and update. The behaviour shouldn't be any different.

The problem may be due to the fact you've set it up as an alias. Remove that alias & see what happens.

Ohhh, i see you have two aliases.

You have a One-One connection and both tables have a foreignKey fields. Remove one foreignKey, it's not neccessary. Let's a profile hands a user_id and user don't have a profile_id and it will be good



32.7k

It's not related to alias and i don't want to remove any foreign keys. The DB arch SHOULD be like this. Any other ideas ? Maybe @Phalcon has some ?



1.6k
Accepted
answer

Did you see you have a cycled link?

#user#            #profile#
- id              - id
- profile_id      - user_id

You have a link from Profile to User and from User to Profile. It's a bad idea at all, you have a information duplicate, it's not normalized structure. If you insist that structure is ok that only thing you can do, create records separetelly from each other.

First create User, and then create Profile. That's all.



32.7k

You are right Pavel. I just realised that. Thank you !