Sequence Generated Value Not Populated In Ar

Hi everyone,

I have a doubt about saving two models with HAS_ONE relation, i did it in two ways. The records are being saved in database, but in the first case i can’t retrieve the $user->id_user after $user->save() function. In the second case i try to receive the $person->user->id_user (another manner) and works fine.

I am using PostgreSQL and my tables are modeled as you can see below (DDL). My FK on table tb_user is also a PK so Yii can recognize that there’s a HAS_ONE relation. Also, id_user/id_person (UNIQUE, SERIAL) is an another key that I use on every table to control tuples in a different way.

DDL tb_person:




CREATE TABLE tb_person(

id_person 			INTEGER PRIMARY KEY DEFAULT NEXTVAL('seq_tb_person'),

full_name 			VARCHAR(100) NOT NULL,

birthdate 			DATE,

);



DDL tb_user:




CREATE TABLE tb_user(

id_user 	INTEGER DEFAULT NEXTVAL('seq_tb_user'),

id_person 	INTEGER,

username 	VARCHAR(64) NOT NULL,

password 	VARCHAR(64) NOT NULL,

PRIMARY KEY(id_person),

UNIQUE(username),

UNIQUE(id_user),

FOREIGN KEY(id_person) REFERENCES tb_person(id_person) ON UPDATE CASCADE ON DELETE CASCADE

);



Person Model:




    public function relations()

    {

        return array(

            'user' => array(self::HAS_ONE, 'User', 'id_person'),

        );

    }



User Model:




    public function relations()

    {

        return array(

            'person' => array(self::BELONGS_TO, 'Person', 'id_person'),

        );

    }



First case:




    $person = new Person();

    $user = new User();

    

    $person->attributes = $_POST['Person'];

    $user->attributes = $_POST['User'];

    

    $person->save();

    $user->id_person = $person->id_person; 

    $user->save();


    var_dump($user->id_user);



[color="#FF0000"]The first case will print null.[/color]

Second case:




    $person = new Person();

    $user = new User();

    

    $person->attributes = $_POST['Person'];

    $user->attributes = $_POST['User'];

    

    $person->save();

    $user->id_person = $person->id_person; 

    $user->save();


    var_dump($person->user->id_user);



[color="#008000"]The second case will print the user id correctly.[/color]

My question is:

1ª - Why in the first case i can’t retrieve the id_user and in the second case i can?

Since $user->id_user is not a primary key it is not populated after save(). It is only filled in the database because it has a default value. The second example you posted triggers a select from the database that loads all the values, because it is an example of lazy loading. The first one does not.

just change the line




 $user->id_person = $person->id;