I use the following two models:
CREATE TABLE `Customer` (
`customerid` int(10) unsigned NOT NULL auto_increment COMMENT 'Kundennummer',
`name` varchar(255) NOT NULL,
PRIMARY KEY (`customerid`),
KEY `fk_Customer_Users` (`User`),
CONSTRAINT `fk_Customer_Users` FOREIGN KEY (`User`) REFERENCES `Users` (`idUsers`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB
And
CREATE TABLE `Object` (
`objectid` int(10) unsigned NOT NULL auto_increment,
`name` varchar(255) NOT NULL,
`customerid` int(10) unsigned NOT NULL)
PRIMARY KEY (`objectid`),
KEY `fk_object_customer` (`customerid`),
CONSTRAINT `fk_object_customer` FOREIGN KEY (`customerid`) REFERENCES `Customer` (`customerid`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB
So there is a 1:n relation. Yii perfectly corrects sets the relations when creating the models:
public function relations()
{
return array(
'customer' => array(self::BELONGS_TO, 'Customer', 'customerid'),
);
}
public function relations()
{
return array(
'objects' => array(self::HAS_MANY, 'Object', 'customerid'),
);
}
Now, after inserting some random data to customer, i try to insert a Object. It fails:
CDbCommand failed to execute the SQL statement: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`ZimmerDienst/Object`, CONSTRAINT `fk_object_customer` FOREIGN KEY (`customerid`) REFERENCES `Customer` (`customerid`) ON DELETE NO ACTION ON UPDATE NO ACTION)
because in the ObjectController/actionCreate.php this line isn't working as expected:
$model->attributes=$_POST['Object'];
it works by appending this line:
$model->customerid = $_POST['Object']['customerid'];
so the automatic assignment of $model->attributes doesn't seem to work with foreign key definitions ? Sorry for having a long breath for such a small problem; english is my foreign language, thank you.