Save related models


if I have two model related by the primary key "id" I am obligated to save model A before to assign the foreign key to model B.

But if the validation of model B fails, how I can remove (rollback) the model A inserted…

The best way is use transaction????




What you try to do is a very common task.

You find tons of resources how to do it in the forum, the guide or even the web when using google…


The best thing would be to validate all the Models BEFORE saving anything in the first place.

Most of the times you find a good example in the guide, like this one:

It depends for example if your DB does support transactions in the first place.


MetaCrawler, while everybody strongly refuse to answhere this question? Your link is not “good” for me. While don’t show us this resource on google? I spend many hours on google, but can’t find answere? Just HELP US PLEASE!!!

Sorry - I don’t want to sound rude, but:

Please explain in details why the link is not good for you?

What part of the provided link do you not understand?

Or explain your question better / in more detail.

Or explain what exactly you excpect to hear from me?

The link I provided describes very good how to proceed:

if ($user->load(Yii::$app->request->post()) && $profile->load(Yii::$app->request->post())) 


    $isValid = $user->validate();

    $isValid = $profile->validate() && $isValid;

    if ($isValid) {



        return $this->redirect(['user/view', 'id' => $id]);



On which part of above code do you have questions?

It validates BOTH models BEFORE actually saving any of them.

Even when you use transactions - you should validate both models.

Somehow I doubt that you have "spend many hours on google" when you have found nothing that helped you making any progress. When I look in google for "yii2 use transactions" or "yii2 save related models" or "Yii2 save mutliple models" I find hundrets of results… (And by the way: That is the reason nobody is answering - because it is easy to find everywhere)

[EDIT: OH - sorry. I just realized you are not the same person who has started this thread. Anyway - the points I wrote above are all still valid.]


MetaCrawler, first to thanks for answere!!!

Second, i was not precise enough. If i have classical master/child form, master have many record and you mast have id from master before,how to solve it. I found only one very complicated solution in Yii 1.x! Any comment and sugestion will be wellcomme.



I don’t understand your question, and so it’s impossible for me to answer it. Probably no one can.

Please try to state your problem clearly.

softark, in relational database theorie casical example is invoice and invoice items. How to do it in yii2. Nothing more, nothing less. Dinamic form, or tabular xxxx is not good solution, for my ponint of view!

Thanks in advice softark.


What you said means nothing more than a mere declaration of a relation - "An Invoice has many Items."

It’s OK. We all understand it. But your question is too vague to be answered. I still don’t understand what you are asking.

Please let me know what you have done so far and what do you find difficult in particular.

Would you please show us your code?

How to make relation between master and child form? Master is ActiveForm and child is gred.

Basically, you should consider creating ONE ActiveForm which contains a master model and an array of related child models. You might want to use a grid for the child models. That’s OK. Include it in the form.

The main model can be treated easily in the standard way. And the related models can be (and should be) treated using the tabular input approach.

First, you must learn how to handle tabulamr input.

Tabular Input:

And also how to use multiple models in one form.

Multiple Models:

As you may notice, you will need to combine the 2 approaches above mentioned.

Well, frankly saying, it’s not that simple and easy. I may or may not write some example for it, because it will be a help for the community as a whole. But I’m not sure whether I may have time to do it. Hopefully someone else may write a good example.

Please remember, we are all volunteers, not your paid tutors. You can never expect us to answer your particular questions. We may or may not answer your questions. It depends.

If you want a good answer, at least you have to try to write a good question.

While You make me shame?

If I can’t make master/child form with ActiveRecord as source for both, ActiveFom for master and Gred for child, then Yii2 isn’t useful for me. Tabular input is sado/mazo think not useful for me. I need commotion as Active form!!! ActiveRecord, not array.

"If you want a good answer, at least you have to try to write a good question.", I was asking only basic principles!

"We may or may not answer your questions.", if You choose to work Open Source, it mean You have wish to help people!

I don’t want to offend you, my friend. Please calm down.

You are right. I don’t think that Yii2 can give you a ready-made solution for your needs.

An array of ActiveRecords. Did you read the sections of the guide that I linked?

I don’t think so.


I don’t say that I’m not willing to help someone, but it’s not always possible … sometimes because I don’t have enough time, other times because I myself don’t know the answer.

I know that my english is bad and my question sometimes could be unclear.

The link that you share I had already seen and it hasn’t the answer to my question…

Model B rules:

public function rules()


        return [

            [['trip_id', 'from'], 'required'],


As you see "trip_id" is required, so I need to save Model A (Trip) before to get the id to assign at trip_id attribute.

So I can’t validate both models before saving … Maybe I should remove the rule?

The purpose of validation rules is to validate user input.

Thank you! Now is clear!