Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

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();?
              }
      }
}


6.5k
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.



6.2k
edited May '15

Thanks a lot, that works great!

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

```php

$this->save();

```

So the model will look like this:

```php 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.