Hi.
I have noticed that there is a horde of documentation about the different query options when using relational active record, but there is no mention whatsoever about creating and updating records using this method. From the tests that I have done, it would appear that `new’ models and ->save() is unable to update the related tables.
Is this correct, or have I incorrectly defined my relationships?
Example tables:
[sql]
– address table
CREATE TABLE address (
address_id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
address_line_1 VARCHAR(20) NOT NULL DEFAULT '',
address_line_2 VARCHAR(20) NOT NULL DEFAULT '',
city VARCHAR(20) NOT NULL DEFAULT '',
postcode VARCHAR(<img src='http://www.yiiframework.com/forum/public/style_emoticons/default/cool.gif' class='bbc_emoticon' alt='8)' /> NOT NULL DEFAULT '',
PRIMARY KEY (address_id)
);
– user table
CREATE TABLE user (
user_id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
address_id INT(10) UNSIGNED,
user_name VARCHAR(20) NOT NULL,
password CHAR(32) NOT NULL DEFAULT '',
first_name VARCHAR(20) NOT NULL DEFAULT '',
last_name VARCHAR(20) NOT NULL DEFAULT '',
telephone_number VARCHAR(16) NOT NULL DEFAULT '',
alt_telephone_number VARCHAR(16) NOT NULL DEFAULT '',
admin_user ENUM('Y','N') NOT NULL DEFAULT 'N',
PRIMARY KEY (user_id),
CONSTRAINT user_in_address_mva
FOREIGN KEY (address_id) REFERENCES address(address_id)
);
[/sql]
User Model:
class User extends CActiveRecord
{
...
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'address'=>array(self::HAS_ONE, 'Address', 'address_id'),
);
}
...
I have tested in the following way using the yiic shell:
yiic> $user = new User
yiic> $user->user_name = 'user1'
yiic> $user->first_name = 'FirstName'
yiic> $user->address->address_line_1 = '10 Downing Street'
yiic> $user->address->postcode = 'SW1A 2AA'
yiic> $user->save()
Check:
yiic> $user = User::model()->findByPk(1) // assuming the above inserted the row with user_id = 1
yiic> echo $user->address->address_line_1
Essentially, creating a new record results in only a row being added to the user table, but the address table remains untouched. I have tried adding a BELONGS_TO relationship to the Address model too, but this does not make any difference.
Assuming that insert and update are not possible, can someone recommend the best way of populating a user and the related address in a single form. I can’t seem to find any documentation that covers this.
TIA,
Paul.