Progredi Digital
Progredi Digital

Reputation: 341

CakePHP hasOne association returns array of empty fields for non-existant record

Have User and UserProfile models. User model has hasOne association with UserProfile. UserProfile mysql table is empty. When I do $this->User->find('all', array('contain' => array('UserProfile'))) instead of an empty UserProfile array, as you would expect, I get an array populated with empty fields that correspond to schema:


Array
(
    [0] => Array
        (
            [User] => Array
                (
                    [id] => 1
                    [firstname] => Joe
                    [surname] => Bloggs
                    [email] => [email protected]
                    [password] => $2a$10$re4r7AXWQcXgkKcabUqmtO6j.7p2bA1t2SLeG93eVsiDPBgGaeXRS
                    [enabled] => 1
                    [user_group_id] => 1
                    [created] => 2014-06-26 15:01:38
                    [modified] => 2014-06-26 15:01:38
                )

            [UserProfile] => Array
                (
                    [id] => 
                    [job_title] => 
                    [user_id] => 
                    [enabled] => 
                    [created] => 
                    [modified] => 
                )

        )

Anyone seen this and know how to fix it?!

Upvotes: 2

Views: 899

Answers (1)

Reactgular
Reactgular

Reputation: 54791

This is correct behavior because the hasOne association is not optional. If you want to make it optional, then change it to a hasMany and only ever create one record.

Cake is performing a LEFT JOIN from User to UserProfile and the query result produced NULL values for the missing record. This is the same result you would get if you executed the SQL in an editor outside of Cake.

Upvotes: 4

Related Questions