S
S
sacred12015-02-22 18:56:26
Yii
sacred1, 2015-02-22 18:56:26

Saving related data yii1 (active record)?

Good day to all. Quite recently I started to deal with yii, so do not blame me. For example, we have two tables. First table authors with fields - `id`(pk),`name`,`surname`, second table posts with fields - `post_id`,`post` and `author_id` where this field is a foreign key (on delete cascade on update cascade). And actually the question is how, when adding data, add the last id from the authors table to the posts table of the author_id field.
As I tried and failed, the controller itself:

$model_authors = new Authors;
$model_posts= new Posts;
        if(isset($_POST['Authors ']) && isset($_POST['Posts '])){

            $model_authors ->attributes=$_POST['Authors '];
            $model_posts->attributes=$_POST['Posts '];
            $model_posts->author_id = $model_authors->id;
       }

In the controller itself, it’s completely impossible to pick up this identifier (id), it’s trite that it doesn’t see it when I look at var_dump, what it saves.
I also tried through afterSave in the model itself. authors model:
protected function afterSave(){
        parent::afterSave();
        $post= new Posts;
        $post->author_id = $this->id;
        $post->save();
    }

Here, if you look through var_dump $this->id, this is different and there is our lastinsertid, but why the saving also does not occur.
I would be very grateful if you could clarify!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Kolokolnikov, 2015-02-22
@maxmirazh33

In the first case, BEFORE saving the $model_authors model, it does not have an id (if it is MySQL and the id is auto-incrementing).
The second case should work, here you already need to look at the Posts model, validation may not pass or something like that.

M
Mikhail Pomytkin, 2015-02-24
@DanteXXI

Look towards Transactions in yii. As a result, there will be something like this (did not check for performance):

$author = new Author();
$post = new Post();
if (isset($_POST["Post"]) && isset($_POST["Author"])) {
    $author->setAttributes($_POST["Author"]);
    $post->setAttributes($_POST["Post"]);
    if ($author->validate()) {
        $transaction = $author->getDbConnection()->beginTransaction();
        try {
            $author->save();
            $transaction->commit();
            $post->author_id = $author->author_id;
            if ($post->validate()) {
                $post->save();
                $transaction->commit();
            }
            else {
                $transaction->rollback();
            }
        }
        catch(Exception $e) {
            $transaction->rollback();
        }
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question