getDb() public static méthode

By default, the "db" application component is used as the database connection. You may override this method if you want to use a different database connection.
public static getDb ( ) : Connection
Résultat Connection the database connection used by this AR class.
 protected function beginTransaction()
 {
     $db = $this->owner->getDb();
     if ($db->getTransaction() === null) {
         $this->transaction = $db->beginTransaction();
     }
 }
Exemple #2
0
 /**
  * @inheritdoc
  */
 public static function getDb()
 {
     if (Configs::db() !== null) {
         return Configs::db();
     } else {
         return parent::getDb();
     }
 }
Exemple #3
0
 /**
  * @inheritdoc
  */
 public static function getDb()
 {
     if (Configs::instance()->db !== null) {
         return Configs::instance()->db;
     } else {
         return parent::getDb();
     }
 }
Exemple #4
0
 public function save($runValidation = true, $attributes = null)
 {
     if ($runValidation && !$this->validate($attributes)) {
         Yii::info('Dynamic model data were not save due to validation error.', __METHOD__);
         return false;
     }
     $db = $this->entityModel->getDb();
     $transaction = $db->beginTransaction();
     try {
         foreach ($this->handlers as $handler) {
             $handler->valueHandler->save();
         }
         $transaction->commit();
     } catch (\Exception $e) {
         $transaction->rollBack();
         throw $e;
     }
 }
 /**
  * @return \yii\db\Connection the database connection used by this AR class.
  */
 public static function getDb()
 {
     if (isset(Yii::$app->params['audittrail.db'])) {
         return Yii::$app->get(Yii::$app->params['audittrail.db']);
     } else {
         return parent::getDb();
     }
     // return Yii::$app->get('dbUser');
 }
Exemple #6
0
 public static function add($tags, $blog_id)
 {
     $data = [];
     if (Tags::validateTags($tags)) {
         $tags = explode(',', $tags);
     }
     foreach ($tags as $tag) {
         array_push($data, ['name' => $tag, 'blog_id' => $blog_id]);
     }
     parent::getDb()->createCommand()->batchInsert(self::tableName(), ['name', 'blog_id'], $data)->execute();
 }
 /**
  * @param $position
  * @return bool
  * @throws \yii\db\Exception
  */
 public function insertTo($position)
 {
     if ($this->getValue() == $position) {
         return true;
     }
     // 59 -> 56 = 58 57 56
     // 56 -> 59 = 57 58 59
     $start = $this->getValue();
     $end = $position;
     if ($start == null || $start == 0) {
         $this->setInsertSort();
         $this->owner->save();
         return true;
     }
     $direction = $start > $end ? static::DirectionDown : static::DirectionUp;
     $query = $this->getQuery();
     $query->andWhere(['between', $this->attributeName, min($start, $end), max($start, $end)]);
     $query->getSortBehavior()->sort();
     /**
      * @var ISortableActiveRecord[]|ActiveRecord[] $items
      */
     $items = $query->all();
     $transaction = $this->owner->getDb()->beginTransaction();
     try {
         foreach ($items as $index => $item) {
             if ($item->getPrimaryKey() == $this->owner->getPrimaryKey()) {
                 $item->getSortBehavior()->setSort($position);
                 $item->save();
             } else {
                 $item->getSortBehavior()->setSort($item->getSortBehavior()->getValue() + ($direction == static::DirectionDown ? 1 : -1));
                 $item->save();
             }
         }
         /* @TODO сделать фикс позиций, что бы не перескакивало и не было дублей */
         $transaction->commit();
     } catch (\Exception $ex) {
         $transaction->rollBack();
         return false;
     }
     return true;
 }
Exemple #8
0
 /**
  * Delete all SEO data for ActiveRecord
  * @param ActiveRecord $owner
  */
 public static function deleteAll(ActiveRecord $owner)
 {
     $owner->getDb()->createCommand()->delete(self::tableName($owner), ['model_id' => $owner->getPrimaryKey()])->execute();
 }
 /**
  * Convert aggregate query from Kendo UI to DB aggregate functions
  *
  * @param array $aggregates usually values of $_POST['aggregates']
  * @param ActiveRecord $model model for generation aggregate functions
  * @return array aggregate functions for Query::select()
  */
 public static function aggregate($aggregates, ActiveRecord $model)
 {
     if (!$aggregates || !is_array($aggregates)) {
         return [];
     }
     $db = $model->getDb();
     $attributes = $model->attributes();
     $aggregateFunctions = static::AGGREGATE_FUNCTIONS;
     $functions = [];
     foreach ($aggregates as $aggregate) {
         if (!empty($aggregate['aggregate']) && isset($aggregateFunctions[$aggregate['aggregate']]) && !empty($aggregate['field']) && in_array($aggregate['field'], $attributes)) {
             $funcName = $aggregateFunctions[$aggregate['aggregate']];
             $functions[] = $funcName . '(' . $db->quoteColumnName($aggregate['field']) . ') ' . ' AS ' . $db->quoteColumnName($aggregate['aggregate'] . '_' . $aggregate['field']);
         }
     }
     return $functions;
 }
 /**
  * Removed
  *
  * @param mixed $id the id of the class to remove from link table
  */
 protected function unlink($id)
 {
     ActiveRecord::getDb()->createCommand()->delete($this->ownerLinkTable, [$this->ownerLinkTableAttribute => $id])->execute();
 }
 /**
  * Relation to model translation
  *
  * @param $locale
  * @return ActiveQuery
  */
 public function getTranslation($locale = null)
 {
     $locale = $locale ?: Yii::$app->language;
     return $this->owner->hasOne($this->translationModelName, [$this->translationOwnerField => $this->ownerPrimaryKey])->from(['content' => call_user_func([$this->translationModelName, 'tableName'])])->innerJoin(['lang' => Language::tableName()])->where('lang.locale = :locale', [':locale' => $locale])->andWhere('content.' . $this->owner->getDb()->quoteColumnName($this->languageField) . ' = lang.id');
 }
 /**
  * Links uploaded file to its owner.
  *
  * @param mixed $ownerId
  * @param mixed $id
  */
 protected function link($ownerId, $id)
 {
     ActiveRecord::getDb()->createCommand()->insert($this->ownerLinkTable, [$this->ownerLinkTableAttribute => $ownerId, $this->ownerLinkTableAttribute => $id])->execute();
 }
Exemple #13
0
 /**
  * Save model of settings
  * @param ActiveRecord $model Model to save
  * @param array $requestParams Request parameters
  * @return bool
  */
 protected function saveSettingsModel(ActiveRecord $model, array $requestParams)
 {
     $success = false;
     $transaction = $model->getDb()->beginTransaction();
     try {
         $model->load($requestParams);
         if ($model->save()) {
             $transaction->commit();
             Yii::$app->interfaceSettings->refreshUserInterfaceSettings($model->user_id, $model->interface_id);
             $success = true;
         } else {
             throw new Exception();
         }
     } catch (Exception $e) {
         if ($transaction->isActive) {
             $transaction->rollBack();
         }
     }
     // trigger an event
     $this->trigger(self::EVENT_SAVE_SETTING, new ExtraDataEvent(['extraData' => ['model' => $model, 'success' => $success]]));
     return $success;
 }
Exemple #14
0
 /**
  * @param \yii\db\ActiveRecord $model
  */
 public function addDirtyModel($model)
 {
     // --- debug - start ------------------------------------------------------
     // make sure there's always only one instance referencing a DB record
     $dsn = $model->getDb()->dsn;
     $table = $model->tableName();
     $pk = $model->getPrimaryKey();
     $modelId = "{$dsn}:{$table}:{$pk}";
     if (array_key_exists($modelId, $this->_dirtyModelsInfo)) {
         $storedModel = $this->_dirtyModelsInfo[$modelId];
         if ($storedModel !== $model) {
             throw new \yii\base\NotSupportedException("Can't handle two instances for tabel '{$table}', id '{$pk}' (dsn '{$dsn}').");
         }
     }
     $this->_dirtyModelsInfo[$modelId] = $model;
     // --- debug - end --------------------------------------------------------
     $this->_dirtyModels->attach($model);
 }
 /**
  * @overriding
  * @see \yii\base\Object::init()
  */
 public function init()
 {
     parent::init();
     try {
         //Initialize template model of the mail AR.
         $this->_templateModel = Yii::createObject($this->modelClass);
         $this->_db = $this->_templateModel->getDb();
         if ($this->sentByBehavior) {
             $this->sentByBehavior = Yii::createObject($this->sentByBehavior);
         }
     } catch (\ReflectionException $refE) {
         $route = explode('/', Yii::$app->getRequest()->resolve()[0]);
         if (isset(Yii::$app->coreCommands()[$route[0]]) || empty($route[0])) {
             return;
         }
         $action = isset($route[1]) ? $route[1] : '';
         if (!$this->installerMode) {
             $err = "Model class <{$this->modelClass}> not found." . PHP_EOL;
             $err .= "Please install the module first before using it.";
             $err .= "(Instruction in QuickStart section of README file.)" . PHP_EOL;
             $err .= "If the module is already installed, ";
             $err .= "please check if the attribute \"modelClass\" defines an available Model class." . PHP_EOL;
             $this->stderr($err, Console::FG_RED);
             Yii::$app->end(1);
         } elseif (!in_array($action, array_keys($this->installerActions))) {
             $err = 'Only actions: ' . implode(', ', array_keys($this->installerActions));
             $err .= ' are available in current installer mode.' . PHP_EOL;
             $err .= 'Please set option "installerMode" to false (default) to use other commands.' . PHP_EOL;
             $this->stderr($err, Console::FG_RED);
             Yii::$app->end(1);
         }
     } catch (Exception $e) {
         throw $e;
     }
 }
 protected function unlinkMany($name, $except = [], $delete = false)
 {
     $relation = $this->getOwnerRelation($name);
     if ($relation->via !== null) {
         if (is_array($relation->via)) {
             /* @var $viaRelation ActiveQuery */
             list($viaName, $viaRelation) = $relation->via;
             $viaClass = $viaRelation->modelClass;
             //                unset($this->_related[$viaName]);
         } else {
             $viaRelation = $relation->via;
             $viaTable = reset($relation->via->from);
         }
         $condition = [];
         $nulls = [];
         foreach ($viaRelation->link as $a => $b) {
             $nulls[$a] = null;
             $condition[$a] = $this->owner->{$b};
         }
         if (!empty($viaRelation->where)) {
             $condition = ['and', $condition, $viaRelation->where];
         }
         if ($except) {
             $values = $this->getLinkValues($except, array_flip($relation->link));
             $condition = ['and', $condition, ['not in', array_values($relation->link), array_unique($values, SORT_REGULAR)]];
         }
         if (is_array($relation->via)) {
             /* @var $viaClass ActiveRecordInterface */
             if ($delete) {
                 $viaClass::deleteAll($condition);
             } else {
                 $viaClass::updateAll($nulls, $condition);
             }
         } else {
             /* @var $viaTable string */
             /* @var $command Command */
             $command = ActiveRecord::getDb()->createCommand();
             if ($delete) {
                 $command->delete($viaTable, $condition)->execute();
             } else {
                 $command->update($viaTable, $nulls, $condition)->execute();
             }
         }
     } else {
         /* @var $relatedModel ActiveRecordInterface */
         $relatedModel = $relation->modelClass;
         if (!$delete && count($relation->link) == 1 && is_array($this->owner[$b = reset($relation->link)])) {
             // relation via array valued attribute
             $this->owner->{$b} = [];
             //                $this->owner->save(false);
         } else {
             $nulls = [];
             $condition = [];
             foreach ($relation->link as $a => $b) {
                 $nulls[$a] = null;
                 $condition[$a] = $this->owner->{$b};
             }
             if (!empty($relation->where)) {
                 $condition = ['and', $condition, $relation->where];
             }
             if ($except) {
                 $values = $this->getLinkValues($except, $relation->link);
                 if ($values) {
                     $condition = ['and', $condition, ['not in', array_values($relation->link), array_unique($values, SORT_REGULAR)]];
                 }
             }
             if ($delete) {
                 $relatedModel::deleteAll($condition);
             } else {
                 $relatedModel::updateAll($nulls, $condition);
             }
         }
     }
     //        unset($this->_related[$name]);
 }
 /**
  * Returns queries that contain necessary joins and condition
  * to select only those records which are related directly or indirectly
  * with the current user.
  * @param ActiveRecord $model     must have the AuthorizerBehavior attached
  * @param array $relations        list of model relations to check, supports dot notation for indirect relations
  * @param IdentityInterface $user if null, Yii::$app->user->identity will be used
  * @param array $baseConditions
  * @param array $baseParams
  * @return ActiveQuery[]
  */
 public function getCompositeRelatedUserQuery($model, array $relations, $user, $baseConditions = [], $baseParams = [])
 {
     $schema = $model->getDb()->getSchema();
     $userPk = array_map([$schema, 'quoteSimpleColumnName'], $user::primaryKey());
     $result = [];
     if (count($userPk) > 1) {
         throw new InvalidCallException('Composite primary key in User model is not supported.');
     } else {
         $userPk = reset($userPk);
     }
     $mainQuery = $model->find();
     if (empty($mainQuery->from)) {
         $mainQuery->from = [$model->tableName() . ' t'];
     }
     $mainQuery->distinct = true;
     foreach ($relations as $relationName) {
         if (($pos = strpos($relationName, '.')) === false) {
             $relation = $model->getRelation($relationName);
             if (!$relation->multiple) {
                 $query = $mainQuery;
             } else {
                 $query = $model->find();
                 if (empty($query->from)) {
                     $query->from = [$model->tableName() . ' t'];
                 }
             }
             $query->innerJoinWith([$relationName => function ($query) use($relation, $relationName) {
                 /** @var ActiveRecord $modelClass */
                 $modelClass = $relation->modelClass;
                 return $query->from([$modelClass::tableName() . ' ' . $relationName]);
             }]);
             $column = $schema->quoteSimpleTableName($relationName) . '.' . $userPk;
             $query->orWhere($column . ' IS NOT NULL AND ' . $column . ' = :current_user_id');
             $query->addParams([':current_user_id' => $user->getId()]);
             if ($relation->multiple) {
                 $query->andWhere($baseConditions, $baseParams);
                 $result[] = $query;
             }
         } else {
             $userRelationName = substr($relationName, $pos + 1);
             $relationName = substr($relationName, 0, $pos);
             $relation = $model->getRelation($relationName);
             /** @var ActiveRecord $relationModel */
             $relationModel = new $relation->modelClass();
             $userRelation = $relationModel->getRelation($userRelationName);
             $userQuery = $relationModel->find();
             if (empty($userQuery->from)) {
                 $userQuery->from = [$relationModel->tableName() . ' t'];
             }
             $userQuery->distinct();
             $userQuery->select($this->quoteColumn('t', $relationModel::primaryKey(), $schema));
             //$userQuery->innerJoinWith($userRelationName);
             $userQuery->innerJoinWith([$userRelationName => function ($query) use($userRelation, $userRelationName) {
                 /** @var ActiveRecord $modelClass */
                 $modelClass = $userRelation->modelClass;
                 return $query->from([$modelClass::tableName() . ' ' . $userRelationName]);
             }]);
             $userQuery->andWhere($schema->quoteSimpleTableName($userRelationName) . '.' . $userPk . ' = :current_user_id');
             $command = $userQuery->createCommand($model->getDb());
             $query = $model->find();
             if (empty($query->from)) {
                 $query->from = [$model->tableName() . ' t'];
             }
             $query->distinct();
             //$query->innerJoinWith($relationName);
             $query->innerJoinWith([$relationName => function ($query) use($relation, $relationName) {
                 /** @var ActiveRecord $modelClass */
                 $modelClass = $relation->modelClass;
                 return $query->from([$modelClass::tableName() . ' ' . $relationName]);
             }]);
             $fk = $this->quoteColumn($relationName, $relationModel::primaryKey(), $schema);
             $query->orWhere('COALESCE(' . (is_array($relationModel::primaryKey()) ? 'ROW(' . $fk . ')' : $fk) . ' IN (' . $command->getSql() . '), false)');
             $query->addParams([':current_user_id' => $user->getId()]);
             $query->andWhere($baseConditions, $baseParams);
             $result[] = $query;
         }
     }
     $mainQuery->andWhere($baseConditions, $baseParams);
     $result[] = $mainQuery;
     return $result;
 }
Exemple #18
0
 public static function getDb()
 {
     return Auditing::current() ? Auditing::current()->getDb() : parent::getDb();
 }
 public function beforeTransaction()
 {
     //        if (!isset($this->owner->getDb()->transaction->isActive))  {
     $this->transaction = $this->owner->getDb()->beginTransaction();
     //        }
 }
 /**
  * For each related model, try to save it first.
  * If set in the owner model, operation is done in a transactional way so if one of the models should not validate
  * or be saved, a rollback will occur.
  * This is done during the before validation process to be able to set the related foreign keys.
  * @param ActiveRecord $model
  * @param ModelEvent $event
  * @return bool
  */
 public function _saveRelatedRecords(ActiveRecord $model, ModelEvent $event)
 {
     if ($model->isNewRecord && $model->isTransactional($model::OP_INSERT) || !$model->isNewRecord && $model->isTransactional($model::OP_UPDATE) || $model->isTransactional($model::OP_ALL)) {
         $this->_transaction = $model->getDb()->beginTransaction();
     }
     try {
         foreach ($this->relations as $relationName) {
             if (array_key_exists($relationName, $this->_oldRelationValue)) {
                 // Relation was not set, do nothing...
                 $relation = $model->getRelation($relationName);
                 if (!empty($model->{$relationName})) {
                     if ($relation->multiple === false) {
                         // Save Has one relation new record
                         $pettyRelationName = Inflector::camel2words($relationName, true);
                         $this->_saveModelRecord($model->{$relationName}, $event, $pettyRelationName, $relationName);
                     } else {
                         // Save Has many relations new records
                         /** @var ActiveRecord $relationModel */
                         foreach ($model->{$relationName} as $i => $relationModel) {
                             $pettyRelationName = Inflector::camel2words($relationName, true) . " #{$i}";
                             $this->_validateRelationModel($pettyRelationName, $relationName, $relationModel, $event);
                         }
                     }
                 }
             }
         }
         if (!$event->isValid) {
             throw new Exception("One of the related model could not be validated");
         }
     } catch (Exception $e) {
         if ($this->_transaction instanceof Transaction && $this->_transaction->isActive) {
             $this->_transaction->rollBack();
             // If anything goes wrong, transaction will be rolled back
         }
         $event->isValid = false;
         // Stop saving, something went wrong
         return false;
     }
     return true;
 }