can't retrieve related ar object record from newly inserted ar object


(Btyuest) #1

is this a bug?

i use it in afterSave() to implement a common fuction:

public function afterSave()

{

    $this->post->replyQty += 1;

    $this->post->save();

}

it raise a exception says that $this->post is null


(Qiang Xue) #2

What is $this->post? Is it loaded before you call its save()?


(Poppitypop) #3

Beware pf going into endless loops, Yuest.  You are putting a save in afterSave(), which in turn calls another afterSave(). !


(Btyuest) #4

<?php

class Reply extends CActiveRecord

{

    //…

    public function relations()

    {

        return array(

            'author'=>array(self::BELONGS_TO, 'User', 'userId'),

            'post'=>array(self::BELONGS_TO, 'Post', 'postId'),

        );

    }

    //…

    /*

    protected function afterSave()

    {

        $this->post->replyQuantity += 1;

        $this->post->lastReplyTime = date("Y-m-d H:i:s");

        $this->post->save();

    }

    * this doesn't works, i must use the code below: */

    protected function afterSave()

    {

        $post = Topic::model()->findbyPk($this->postId);

        $post->replyQuantity += 1;

        $post->lastReplyTime = date("Y-m-d H:i:s");

        $post->save();

    }

    protected function afterDelete()

    {

        $this->post->replyQuantity -= 1;

        $this->post->save();

    }//this works when deleting

}


(Qiang Xue) #5

Thanks. This is fixed in SVN.