Same Id Integer For Two Tables

Hey guys, i have a single form for two different models. let’s call the first model “Books” and the second model for “Category”. The primary key in Category is called “bookId” and (funny enough) there’s a relation between the id in Books and bookId in Category (Books id has one Category bookId).

My question is: How to add the same integer number to the two tables when i submit my form from /books/create ?

In the create action, after saving first model, set the primary key of first model to the primary key second model.

i’m kind of lost on how you want to write that code?

My initial thoughts were to do something in a before validate function… but i guess your way is more “clean”. I just can’t see how to write it

If I am not mistakes, you’re collecting category name in the single form, as well. so here is the actionCreate

public function actionCreate()


		$model=new Book;

		// Uncomment the following line if AJAX validation is needed

		// $this->performAjaxValidation($model);






                                $category=new Category;


                                $category->name=... etc




I’ve now tried what you suggested, but it didn’t work. I also tried:


but it didn’t work either. That was a long shot anyway, since id for the table Game is auto increment, and therefore isn’t posted in the form.

I tried it on my system and I worked. I guess you’re data is not validate, so you can’t save it. Have you checked you database and verify if the main model is saved and the autoincrement id works? If yes, everything should work fine. And yes that was a very long shot :)

My problem is that i validate both the models at the same time in order for the error-summary to show for both the tables at the same time. It’s therefore not possible for me to do it in exactly the same way as you do.

Perhaps that’s causes the problem. If you have a foreign key in the second model, even if you somehow validate it, because foreign key constrain of the database you end up having problem. And before saving the first model, you won’t be able to access to its autoincrement primary key. You may used a trick to get a maximum id value of the first model and add 1 to it, to get actual id, but it’s not recommended. You may also paste you view, model code here, maybe sb else can help you.