Say the schema looks like this:
CREATE TABLE `user` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
-- basic user info columns
PRIMARY KEY (`id`)
) ENGINE = InnoDB;
CREATE TABLE `user_profile` (
`user_id` INT UNSIGNED NOT NULL,
`name` VARCHAR(200),
-- other general user profile columns
PRIMARY KEY (`user_id`) ,
CONSTRAINT `fk_user_profile_user1`
FOREIGN KEY (`user_id`) REFERENCES `user` (`id`)
ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE = InnoDB;
CREATE TABLE `client` (
`user_id` INT UNSIGNED NOT NULL,
-- client-specific profile columns
PRIMARY KEY (`user_id`),
CONSTRAINT `fk_client_user1`
FOREIGN KEY (`user_id`) REFERENCES `user` (`id`)
ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE = InnoDB;
In which user_profile has an identifying one-to-one relation to user and client has an identifying one-to-one relation to user. Not all users have a user profile. Not all users are clients. All clients have a user profile (business logic).
I want to be able to access user profile fields from a client model like this:
$client = Client::model->findByPk($id);
echo $client->userProfile->name;
instead of having to use:
echo $client->user->userProfile->name;
But I’m having trouble writing my relationship rules. I wasn’t able to figure the answer from “Relational Active Record” in The Definitive Guide or either of the Yii books. This doesn’t work:
public function relations() {
return array(
'user' => array(self::BELONGS_TO, 'User', 'user_id', 'joinType'=>'INNER JOIN'),
'userProfile' => array(self::HAS_ONE, 'UserProfile', 'user_id'),
);
}
And neither does:
'userProfile' => array(self::HAS_ONE, 'UserProfile', 'user_id', 'through'=>'user'),
nor
'userProfile' => array(self::HAS_ONE, 'UserProfile', 'id', 'through'=>'user'),
As you can see, I’m guessing now.
Any idea would be very welcome.