yii\db\ActiveRecord::insert PHP Method

insert() public method

This method performs the following steps in order: 1. call [[beforeValidate()]] when $runValidation is true. If [[beforeValidate()]] returns false, the rest of the steps will be skipped; 2. call [[afterValidate()]] when $runValidation is true. If validation failed, the rest of the steps will be skipped; 3. call [[beforeSave()]]. If [[beforeSave()]] returns false, the rest of the steps will be skipped; 4. insert the record into database. If this fails, it will skip the rest of the steps; 5. call [[afterSave()]]; In the above step 1, 2, 3 and 5, events [[EVENT_BEFORE_VALIDATE]], [[EVENT_AFTER_VALIDATE]], [[EVENT_BEFORE_INSERT]], and [[EVENT_AFTER_INSERT]] will be raised by the corresponding methods. Only the [[dirtyAttributes|changed attribute values]] will be inserted into database. If the table's primary key is auto-incremental and is null during insertion, it will be populated with the actual value after insertion. For example, to insert a customer record: php $customer = new Customer; $customer->name = $name; $customer->email = $email; $customer->insert();
public insert ( boolean $runValidation = true, array $attributes = null ) : boolean
$runValidation boolean whether to perform validation (calling [[validate()]]) before saving the record. Defaults to `true`. If the validation fails, the record will not be saved to the database and this method will return `false`.
$attributes array list of attributes that need to be saved. Defaults to `null`, meaning all attributes that are loaded from DB will be saved.
return boolean whether the attributes are valid and the record is inserted successfully.
    public function insert($runValidation = true, $attributes = null)
    {
        if ($runValidation && !$this->validate($attributes)) {
            Yii::info('Model not inserted due to validation error.', __METHOD__);
            return false;
        }
        if (!$this->isTransactional(self::OP_INSERT)) {
            return $this->insertInternal($attributes);
        }
        $transaction = static::getDb()->beginTransaction();
        try {
            $result = $this->insertInternal($attributes);
            if ($result === false) {
                $transaction->rollBack();
            } else {
                $transaction->commit();
            }
            return $result;
        } catch (\Exception $e) {
            $transaction->rollBack();
            throw $e;
        }
    }

Usage Example

Beispiel #1
0
 /**
  * @inheritdoc
  */
 public function insert($runValidation = true, $attributes = null)
 {
     $this->trigger(static::EVENT_AFTER_INSERT_TRANSACTION);
     return parent::insert($runValidation, $attributes);
 }
All Usage Examples Of yii\db\ActiveRecord::insert