Active Record implements the Active Record design pattern. The premise behind Active Record is that an individual ActiveRecord object is associated with a specific row in a database table. The object's attributes are mapped to the columns of the corresponding table. Referencing an Active Record attribute is equivalent to accessing the corresponding table column for that record. As an example, say that the Customer ActiveRecord class is associated with the customer table. This would mean that the class's name attribute is automatically mapped to the name column in customer table. Thanks to Active Record, assuming the variable $customer is an object of type Customer, to get the value of the name column for the table row, you can use the expression $customer->name. In this example, Active Record is providing an object-oriented interface for accessing data stored in the database. But Active Record provides much more functionality than this. To declare an ActiveRecord class you need to extend ActiveRecord and implement the tableName method: php The tableName method only has to return the name of the database table associated with the class. > Tip: You may also use the Gii code generator to generate ActiveRecord classes from your > database tables. Class instances are obtained in one of two ways: * Using the new operator to create a new, empty object * Using a method to fetch an existing record (or records) from the database Below is an example showing some typical usage of ActiveRecord: php $user = new User(); $user->name = 'Qiang'; $user->save(); // a new row is inserted into user table the following will retrieve the user 'CeBe' from the database $user = User::find()->where(['name' => 'CeBe'])->one(); this will get related records from orders table when relation is defined $orders = $user->orders; For more details and usage information on ActiveRecord, see the guide article on ActiveRecord.
Since: 2.0
Author: Qiang Xue (qiang.xue@gmail.com)
Author: Carsten Brandt (mail@cebe.cc)
Inheritance: extends BaseActiveRecord
Example #1
33
 public function __set($name, $value)
 {
     if (is_array($value) && count($value) > 0 && !$value[0] instanceof Object || !is_array($value) && !$value instanceof Object) {
         $getter = 'get' . $name;
         /** @var ActiveQuery $query */
         $query = $this->owner->{$getter}();
         /* @var $modelClass ActiveRecord */
         $modelClass = $query->modelClass;
         $value = $modelClass::findAll($value);
     }
     $this->owner->populateRelation($name, $value);
 }
 /**
  * @param ActiveRecord $model
  * @param array $actions Custom actions array in the form of
  * ```php
  * 'name' => function() {
  *
  * }
  * ```
  * @param bool $addDefaultActions If true default actions will be added
  * @return \yii\web\Response
  * @throws BadRequestHttpException
  */
 protected function getCreateUpdateResponse($model, $actions = [], $addDefaultActions = true)
 {
     $defaultActions = [AdminHtml::ACTION_SAVE_AND_STAY => function () use($model) {
         /** @var Controller | CrudControllerTrait $this */
         return $this->redirect(['update', 'id' => $model->getPrimaryKey()]);
     }, AdminHtml::ACTION_SAVE_AND_CREATE => function () use($model) {
         /** @var Controller | CrudControllerTrait $this */
         if ($url = Url::previous($this->createUrlParam)) {
             Url::remember(null, $this->createUrlParam);
             return $this->redirect($url);
         }
         return $this->redirect(['create']);
     }, AdminHtml::ACTION_SAVE_AND_LEAVE => function () use($model) {
         /** @var Controller | CrudControllerTrait $this */
         if ($url = \Yii::$app->request->get('return')) {
             return $this->redirect($url);
         }
         if ($url = Url::previous($this->indexUrlParam)) {
             Url::remember(null, $this->indexUrlParam);
             return $this->redirect($url);
         }
         return $this->redirect(['index']);
     }];
     if ($addDefaultActions) {
         $actions = array_merge($defaultActions, $actions);
     }
     $actionName = \Yii::$app->request->post(AdminHtml::ACTION_BUTTON_NAME, AdminHtml::ACTION_SAVE_AND_LEAVE);
     if (isset($actions[$actionName])) {
         return call_user_func($actions[$actionName]);
     } else {
         throw new BadRequestHttpException('Unknown action: ' . $actionName);
     }
 }
Example #3
0
 /**
  * Process output. Throw error when not success with unknown reason.
  * @param boolean      $success
  * @param ActiveRecord $model
  *
  * @return ActiveRecord
  * @throws \yii\web\ServerErrorHttpException
  */
 protected static function processOutput($success, $model)
 {
     if (!$success && !$model->hasErrors()) {
         throw new ServerErrorHttpException('Error with unknown reason.');
     }
     return $model;
 }
Example #4
0
 /**
  * Find and set order numeric
  */
 public function findOrderNum()
 {
     if (!$this->owner->{$this->attribute}) {
         $maxOrderNum = (int) (new Query())->select("MAX({$this->attribute})")->from($this->owner->tableName())->scalar();
         $this->owner->{$this->attribute} = $maxOrderNum + $this->step;
     }
 }
Example #5
0
 public function init()
 {
     parent::init();
     $this->owner->on(ActiveRecord::EVENT_AFTER_INSERT, [$this, 'save']);
     $this->owner->on(ActiveRecord::EVENT_AFTER_UPDATE, [$this, 'save']);
     $this->owner->on(ActiveRecord::EVENT_BEFORE_DELETE, [$this, 'unlink']);
 }
    public function run()
    {
        $confirm = Yii::t('yii', 'Are you sure you want to delete this item?');
        $js = <<<JS
        \$(".delete-button").click(function(){
            var tr = this.closest('tr');
            var url = \$(this).data('url');
            if (confirm("{$confirm}")) {
                \$.ajax({
                    method: "POST",
                    url: url,
                    success: function(data) {
                        if (data) {
                            tr.remove();
                        }
                    }
                });
            }
        });
JS;
        Yii::$app->view->registerJs($js);
        return GridView::widget(['dataProvider' => new ArrayDataProvider(['allModels' => $this->model->getFiles()]), 'layout' => '{items}', 'tableOptions' => $this->tableOptions, 'columns' => [['class' => 'yii\\grid\\SerialColumn'], ['label' => $this->getModule()->t('attachments', 'File name'), 'format' => 'raw', 'value' => function ($model) {
            return Html::a("{$model->name}.{$model->type}", $model->getUrl());
        }], ['class' => 'yii\\grid\\ActionColumn', 'template' => '{delete}', 'buttons' => ['delete' => function ($url, $model, $key) {
            return Html::a('<span class="glyphicon glyphicon-trash"></span>', '#', ['class' => 'delete-button', 'title' => Yii::t('yii', 'Delete'), 'data-url' => Url::to(['/attachments/file/delete', 'id' => $model->id])]);
        }]]]]);
    }
 /**
  * @param integer $type
  * @param \yii\db\ActiveRecord $object
  */
 public function run($type, $object)
 {
     $pkey = $object->primaryKey();
     $pkey = $pkey[0];
     $data = ['table' => $object->tableName(true), 'model_id' => $object->getPrimaryKey(), 'type' => $type, 'date' => date('Y-m-d H:i:s', time())];
     switch ($type) {
         case self::EVT_INSERT:
             $data['field_name'] = $pkey;
             $this->saveField($data);
             break;
         case self::EVT_UPDATE:
             foreach ($this->updatedFields as $updatedFieldKey => $updatedFieldValue) {
                 $data['field_name'] = $updatedFieldKey;
                 $data['old_value'] = $updatedFieldValue;
                 $data['new_value'] = $object->{$updatedFieldKey};
                 $this->saveField($data);
             }
             break;
         case self::EVT_DELETE:
             $data['field_name'] = $pkey;
             $this->saveField($data);
             break;
         case self::EVT_UPDATE_PK:
             $data['field_name'] = $pkey;
             $data['old_value'] = $object->getOldPrimaryKey();
             $data['new_value'] = $object->{$pkey};
             $this->saveField($data);
             break;
     }
 }
Example #8
0
 public function init()
 {
     $this->id = $this->model->formName();
     $this->action = RequestModule::getPopupUrl(['type' => $this->model->tableName()]);
     $this->fieldConfig = ['template' => '<div class="row">{input}{error}</div>', 'errorOptions' => ['class' => 'errorMessage']];
     parent::init();
 }
Example #9
0
 protected function _delete(ActiveRecord $model)
 {
     $id = Yii::$app->request->post('id');
     $model->findOne($id)->delete();
     //        $model::deleteAll($id);
     return $this->_success();
 }
Example #10
0
 /**
  * Initializes the widget options.
  * This method sets the default values for various options.
  */
 protected function initOptions()
 {
     if (!isset($this->options['id'])) {
         $this->options['id'] = $this->getId();
     }
     $this->clientOptions = ArrayHelper::merge(['form' => $this->form, 'fieldsUrl' => Url::to(['/eav/backend/attribute/fields']), 'modelClass' => $this->model ? $this->model->className() : ''], $this->clientOptions);
 }
Example #11
0
 public static function relation(ActiveRecord $model, $relation_name, $options = [])
 {
     /* @var ActiveRecord|YcmModelUtilTrait $model */
     $relation = $model->getRelation($relation_name);
     $config = [$relation_name, 'widget', 'widgetClass' => Select2::className(), 'data' => RelationHelper::getSelectChoices($model, $relation_name), 'hideSearch' => false, 'options' => ['multiple' => $relation->multiple, 'placeholder' => 'Select...'], 'pluginOptions' => ['allowClear' => true]];
     return ArrayHelper::merge($config, $options);
 }
 /**
  * @test
  */
 public function testRenderDualNotController()
 {
     $controller = new \yii\db\ActiveRecord();
     $controller->attachBehavior('RenderDual', new \yii2renderdual\RenderDual());
     $this->setExpectedException('Exception');
     $render = $controller->renderDual('view', ['foo' => 'bar'], 'foo bar');
 }
 public function run($action)
 {
     $this->type = Yii::$app->request->get('type');
     $this->behaviorName = Yii::$app->request->get('behaviorName');
     $this->galleryId = Yii::$app->request->get('galleryId');
     $pkNames = call_user_func([$this->types[$this->type], 'primaryKey']);
     $pkValues = explode($this->pkGlue, $this->galleryId);
     $pk = array_combine($pkNames, $pkValues);
     $this->owner = call_user_func([$this->types[$this->type], 'findOne'], $pk);
     $this->behavior = $this->owner->getBehavior($this->behaviorName);
     switch ($action) {
         case 'delete':
             return $this->actionDelete(Yii::$app->request->post('id'));
             break;
         case 'ajaxUpload':
             return $this->actionAjaxUpload();
             break;
         case 'changeData':
             return $this->actionChangeData(Yii::$app->request->post('photo'));
             break;
         case 'order':
             return $this->actionOrder(Yii::$app->request->post('order'));
             break;
         default:
             throw new HttpException(400, 'Action do not exists');
             break;
     }
 }
Example #14
0
 /**
  * @param ActiveRecord $model
  */
 public function addErrorMessagesFromModel(ActiveRecord $model)
 {
     foreach ($model->getErrors() as $fieldWithErrors) {
         foreach ($fieldWithErrors as $error) {
             $this->addMessage(null, $error, Message::ALERT);
         }
     }
 }
 /**
  * @param $direction string
  * @param $model ActiveRecord
  * @return array
  */
 protected function getUrl($direction, ActiveRecord $model)
 {
     $url = !empty($this->url) ? $this->url : ['order'];
     $url['direction'] = $direction;
     $url['attribute'] = $this->attribute;
     $url['id'] = $model->getPrimaryKey();
     return $url;
 }
 /**
  * @return string
  */
 public function run()
 {
     if ($this->model->hasProperty('mlConfig') and count($this->model->mlConfig['languages']) > 1) {
         return $this->render('index');
     } else {
         return $this->getInputField($this->attribute);
     }
 }
 /**
  * @covers \opus\base\behaviors\TimestampBehavior::inject
  */
 public function testUpdate()
 {
     $now = new Expression('NOW()');
     $this->mock->expects($this->once())->method('getIsNewRecord')->will($this->returnValue(false));
     $this->mock->expects($this->any())->method('hasAttribute')->will($this->returnValue(true));
     $this->mock->expects($this->once())->method('setAttribute')->with('up', $now);
     $this->mock->validate();
 }
 /**
  * @inheritdoc
  *
  * @param ActiveRecord $owner
  *
  * @throws ErrorException
  */
 public function attach($owner)
 {
     if (!self::$_eventSwitched) {
         Event::on($owner->className(), VekActiveRecord::EVENT_TO_SAVE_MULTIPLE, [self::className(), 'logToSaveMultiple']);
         Event::on($owner->className(), VekActiveRecord::EVENT_SAVED_MULTIPLE, [self::className(), 'logSavedMultiple']);
     }
     parent::attach($owner);
 }
Example #19
0
 /**
  * @param  ActiveRecord $activeRecord
  * @param               $attribute
  * @param null $extension
  *
  * @return string
  */
 public function getFilenameFor($activeRecord, $attribute, $extension = null)
 {
     $path = Inflector::camel2id((new \ReflectionClass($activeRecord))->getShortName());
     $basename = implode('-', $activeRecord->getPrimaryKey(true)) . '-' . $attribute;
     if ($extension) {
         $basename .= '.' . $extension;
     }
     return $path . DIRECTORY_SEPARATOR . $basename;
 }
Example #20
0
 /**
  * @inheritdoc
  */
 public function run()
 {
     foreach ($this->model->getErrors() as $attribute => $messages) {
         foreach ($messages as $key => $message) {
             $this->options['id'] = 'error-' . $attribute . '-' . $key;
             echo \yii\bootstrap\Alert::widget(['body' => $message, 'closeButton' => $this->closeButton, 'options' => $this->options]);
         }
     }
 }
Example #21
0
 /**
  * Get an array representing the properties of a model.
  *
  * @param \yii\db\ActiveRecord $model
  * @return array
  */
 public static function castModel(ActiveRecord $model)
 {
     $attributes = array_merge($model->getAttributes(), $model->getRelatedRecords());
     $results = [];
     foreach ($attributes as $key => $value) {
         $results[Caster::PREFIX_VIRTUAL . $key] = $value;
     }
     return $results;
 }
Example #22
0
 /**
  * 
  * @param ActiveRecord $model
  * @param type $key
  * @param type $index
  * @return type
  */
 protected function renderDataCellContent($model, $key, $index)
 {
     $result = Html::tag('span', $index + 1, ['class' => 'serial-column']);
     if ($model instanceof ActiveRecord && ($primaryKeys = $model->primaryKey()) != []) {
         foreach ($primaryKeys as $primary) {
             $result .= ' ' . Html::activeHiddenInput($model, "[{$index}]{$primary}");
         }
     }
     return $result;
 }
Example #23
0
 /**
  * @inheritdoc
  * @param ActiveRecord $owner
  */
 public function attach($owner)
 {
     $this->attribute = (array) $this->attribute;
     $primaryKey = $owner->primaryKey();
     $primaryKey = is_array($primaryKey) ? array_shift($primaryKey) : $primaryKey;
     if (in_array($primaryKey, $this->attribute, true) && $owner->getIsNewRecord()) {
         $this->attributes[ActiveRecord::EVENT_AFTER_INSERT] = $this->slugAttribute;
     }
     parent::attach($owner);
 }
Example #24
0
 /**
 * update count column
 * @param ActiveRecord $oneData
 * @param $filedArray     update column array
 * @param $step           update count number or update count number array
 * e.g
        $obj = GuestBook::findOne(3);
        $this->_update_data_count($obj, ['up_time'], 1);
 */
 public function _update_data_count(ActiveRecord $oneData, $filedArray, $step)
 {
     $arr = array();
     if (is_array($filedArray) && count($filedArray)) {
         foreach ($filedArray as $_k => $_v) {
             $arr[$_v] = is_array($step) ? $step[$_k] : $step;
         }
     }
     $oneData->updateCounters($arr);
 }
Example #25
0
 public function run()
 {
     $object = app\models\Object::getForClass($this->model->className());
     /** @var \app\modules\shop\models\AddonCategory $addonCategories */
     $addonCategories = app\components\Helper::getModelMap(AddonCategory::className(), 'id', 'name');
     /** @var app\modules\shop\models\Addon $bindedAddons */
     $bindedAddons = $this->model->bindedAddons;
     $addAddonModel = new AddAddonModel();
     return $this->render('addons-widget', ['object' => $object, 'addonCategories' => $addonCategories, 'bindedAddons' => $bindedAddons, 'model' => $this->model, 'form' => $this->form, 'addAddonModel' => $addAddonModel]);
 }
Example #26
0
 public function attributeValue(ActiveRecord $model, $fieldName)
 {
     $complexName = $model->tableName() . '.' . $fieldName;
     $decode = \Yii::$app->params['decode'];
     $key = $model->{$fieldName};
     if ($key !== null && isset($decode[$complexName])) {
         return $decode[$complexName][$key];
     } else {
         return $key;
     }
 }
 /**
  * @inheritdoc
  * @param \yii\db\ActiveRecord $owner
  */
 public function attach($owner)
 {
     //assert owner extends class ActiveRecord
     if (!$owner instanceof ActiveRecord) {
         throw new InvalidConfigException('ArchiveBehavior can only be applied to classes extending \\yii\\db\\ActiveRecord');
     }
     if ($owner->tableSchema->getColumn($this->archiveAttribute) === null) {
         throw new InvalidConfigException(sprintf('The table %s does not contain a column named %s', $owner->tableName(), $this->archiveAttribute));
     }
     parent::attach($owner);
 }
 /**
  * Get available relation choices
  * @param $relation_name
  * @return mixed
  */
 public static function getSelectChoices(ActiveRecord $model, $relation_name)
 {
     $class = $model->className();
     if (!isset(self::$relationsChoices[$class][$relation_name])) {
         self::$relationsChoices[$class][$relation_name] = [];
         $relation = $model->getRelation($relation_name, false);
         if ($relation) {
             self::$relationsChoices[$class][$relation_name] = ModelHelper::getSelectChoices(new $relation->modelClass());
         }
     }
     return self::$relationsChoices[$class][$relation_name];
 }
 /**
  * @return null|string
  */
 public function run()
 {
     /**
      * @var \notgosu\yii2\modules\metaTag\components\MetaTagBehavior $behavior
      */
     $behavior = $this->model->getBehavior('seo');
     if (!$behavior) {
         return null;
     }
     $languageList = $behavior->languages;
     return $this->render('default', ['model' => $this->model, 'languageList' => $languageList]);
 }
Example #30
0
 /**
  *
  * @param \yii\db\ActiveRecord $model
  */
 public function getQuery($model)
 {
     $query = $model->search($this->filters);
     foreach ($this->query as $key => $value) {
         call_user_func([$query, $key], $value);
     }
     /**
      * sort过滤
      */
     $query->addOrderBy($this->sort->orders);
     return $query;
 }