Illuminate\Database\Eloquent\Model::save PHP Method

save() public method

Save the model to the database.
public save ( array $options = [] ) : boolean
$options array
return boolean
    public function save(array $options = [])
    {
        $query = $this->newQueryWithoutScopes();
        // If the "saving" event returns false we'll bail out of the save and return
        // false, indicating that the save failed. This provides a chance for any
        // listeners to cancel save operations if validations fail or whatever.
        if ($this->fireModelEvent('saving') === false) {
            return false;
        }
        // If the model already exists in the database we can just update our record
        // that is already in this database using the current IDs in this "where"
        // clause to only update this model. Otherwise, we'll just insert them.
        if ($this->exists) {
            $saved = $this->isDirty() ? $this->performUpdate($query, $options) : true;
        } else {
            $saved = $this->performInsert($query);
        }
        if ($saved) {
            $this->finishSave($options);
        }
        return $saved;
    }

Usage Example

Example #1
1
 public function updated(Model $model)
 {
     if ($model->isDirty('parent_id')) {
         /**
          * 同步Original数据,是為了清除parent_id的dirty狀態
          */
         $model->syncOriginal();
         $tableName = $model->getTable();
         $oldNode = $model->getOriginal('node');
         if (0 < $model->parent_id) {
             /**
              * @var Model  $parent
              */
             $parent = $model->find($model->parent_id);
             $model->node = $parent->node . $model->id . self::SEPARATOR;
             $model->save();
             //取出原来的level
             $originalLevel = Cache::pull('node-category-original-level-' . $model->id);
             //计算新level与原来的level的差值
             $i = $model->level - $originalLevel;
             DB::table($tableName)->where('node', 'like', $oldNode . '%')->where('id', '<>', $model->id)->update(['level' => DB::raw("level + {$i}"), 'node' => DB::raw("REPLACE(`node`, '{$oldNode}', '{$model->node}')")]);
         } else {
             //修改為頂級分類
             $model->level = 1;
             $model->node = self::SEPARATOR . $model->id . self::SEPARATOR;
             $model->save();
             DB::table($tableName)->where('node', 'like', $oldNode . '%')->where('id', '<>', $model->id)->update(['level' => DB::raw("level - {$model->level}"), 'node' => DB::raw("CONCAT('{$model->node}', `id`, ',')")]);
         }
     }
 }
All Usage Examples Of Illuminate\Database\Eloquent\Model::save
Model