How to use afterSave() to save others models fileds?(有中文)? - Discussion ---
We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Models--- How to use afterSave() to save others models fileds?(有中文)?

Hello! In my question I have two models Post and UserInfo: I want to after save Post and save UserInfo PostNum(+1) filed how I can do? (我有两个模型一个Post,一个UserInfo, 我想在我保存Post之后,UserInfo的postNum也相应的加一,想问大神怎么实现?)



4.7k
Accepted
answer

Hi there :) ... depends what is the relation here or your logick... however, u can use that metod:

class Post extends \Phalcon\Mvc\Model
{
    public function initialize()
    {
        $this->hasOne("id", "Models\UserInfo", "post_id", [
            'alias' => 'Info'
        ]);
    }

  function afterSave() {
      $info = $this->Info;
      $info->num = $info->num+1;
      $info->save();
  }
}

This can be done in controller too. But this is still just idea- i didnt know whan u mean. Be more specific or give us some examples.



27.0k

thanks a lot, 谢谢你,



27.0k
edited Oct '15

Hello? in my function,I do this: but not work:

> 
>   public function afterSave(){
>         if($this->flag!=0){
>             $data = $this->User;
>             if($this->flag==1){
>                 $data->audit = 1;
>             }else if($this->flag==2){
>                 $data->audit = 2;
>             }
>             $data->save();
>             $to = $this->userid;
>             $content = 328;
>             $this->util->sentSocketData('publish',$to,$content);
>           }
>     }

save can sucess, but services(util) cannot work? why

edited Oct '15

In general u cant use shared services in models... if Utils is some helper, plugin, component (shared service). You can still use


public function afterSave(){
        if($this->flag!=0){
            $data = $this->User;
            if($this->flag==1){
                $data->audit = 1;
            }else if($this->flag==2){
                $data->audit = 2;
            }
            $data->save();
            $to = $this->userid;
            $content = 328;

            // Way to get shared service in MODEL
            // You can access session in this way too
            // There is a static way too, if u need
            $util = $this->getDI()->getShared('util');
            $util->sentSocketData('publish',$to,$content);
          }
    }

Not sure if u put this ulit like service, but... :) give more details :)



27.0k

谢谢你,就是这样的了

Got bless bing translator xD Thank you... too :) Good luck there!