I’m trying to use yii to model this kind of relation:
So I made the following tables:
Animal {
int Id (Pk)
varchar Name
}
Dog {
int Id (Pk)
varchar Hair
foreign key, relates this Id with Animal.Id
}
What’s the best way to integrate this with yii? I’ve tried myself and i also read alot of documentation, but could find the answer.
So far i had something like this:
$animal = new Animal;
$dog = new Dog;
$animal->Name = …;
$animal->save();
$animal->refresh() // Tried with and without this line
$dog->Hair = …;
$dog->Id = $animal->Id;
$dog->save(); // I get and error here because he build this query: INSERT INTO Dog (Hair) VALUES(:0ypb) instead of INSERT INTO Dog (Id,Hair) VALUES("the same Id has the Animal that I just created","this is a valid hair")
But probably even if this worked, there must be a better way to manage this relationship in yii I guess.
for creating dogs you first have to create animals and then in your dog form you can have a select menu to select an animal for your dog and then and then in your dogs controller you can do some thing as following
$dog = new Dog;
$dog->attributes = $_POST['Dog'];
$dog->save();
/**
* Creates a new model.
* If creation is successful, the browser will be redirected to the 'view' page.
*/
public function actionCreate()
{
$animal = new Animal;
$dog=new Dog;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Dog']))
{
$animal->nome=$_POST['Dog']['nome'];
$dog->CadeiaDeADN=$_POST['Dog']['CadeiaDeADN'];
if($animal->save()
&& $animal->refresh()
&& $dog->animal_Id = $animal->Id
&& $dog->save())
$this->redirect(array('view','id'=>$dog->Id));
}
$this->render('create',array(
'model'=>$dog,
));
}
With this now I get this:
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 (`myDB`.`dog`, CONSTRAINT `NewForeignKey2` FOREIGN KEY (`animal_Id`) REFERENCES `animal` (`Id`)). The SQL statement executed was: INSERT INTO `dog` (`animal_Id`, `CadeiaDeADN`) VALUES (:yp0, :yp1)
What should I do? I’ve confirmed that he can create animals and retrieve their Id by $animal->Id right after saving them, but still I got this error…