We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Save within model

I have a model Tags, I want to add a function in Tags model, that check if tag exists, if not creat a new record and return an id, but how do I save it within itself's model, do I need to initialize an instance?

class Tags extends Model{
      public function loadTag($string){
              $exist = self::findFirst(array(
                                      'name'=>$string,
              ));

              if($exist){
                  return $exist->id;
              }else{
                  //How to create a new record here within Tag model?
                  //is it best to do with $tag = new Tags();?
              }
      }
}


11.2k
Accepted
answer
edited May '15

If you have filled all fields from outside you can call:


$this->save();

So the model will look like this:

class Tags extends Model{

      public $id;
      public $name;

      public function loadTag($string){
              $exist = self::findFirst(array(
                                      'name'=>$string,
              ));

              if(!$exist){
                  $this->name = $string;
                  $this->save();
                  $id = $this->id;
              }
              else {
                  $id = $exist->id;
              }

              return $id;
      }
}

This, check if item is exist, when not create it and return created tag id.



15.2k
edited May '15

Thanks a lot, that works great!

If you have filled all fields from outside you can call:


$this->save();

So the model will look like this:

class Tags extends Model{

    public $id;
    public $name;

     public function loadTag($string){
             $exist = self::findFirst(array(
                                     'name'=>$string,
             ));

             if(!$exist){
                $this->name = $string;
                 $this->save();
                $id = $this->id;
             }
            else {
                $id = $exist->id;
            }

            return $id;
     }
}

This, check if item is exist, when not create it and return created tag id.