By default this method returns the class name as the table name by calling [[Inflector::camel2id()]]
with prefix [[Connection::tablePrefix]]. For example if [[Connection::tablePrefix]] is tbl_,
Customer becomes tbl_customer, and OrderItem becomes tbl_order_item. You may override this method
if the table is not named after this convention.
public function setInsertSort() { if (!$this->owner->{$this->attributeName}) { $query = $this->getQuery(); $query->select(new Expression('MAX(' . $this->attributeName . ')')); $query->from($this->owner->tableName()); $this->owner->{$this->attributeName} = $query->scalar() + 1; } }
/** * 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; } }
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(); }
/** * @inheritdoc */ public function attach($owner) { parent::attach($owner); //get config from instance if ($this->stateConfig === null || $this->stateAttribute === null) { $this->modelInstance = new $this->owner->modelClass(); $this->stateAttribute = $this->modelInstance->tableName() . '.' . $this->modelInstance->stateAttribute; $this->stateConfig = $this->modelInstance->stateConfig; } }
public function search($params) { /* @var $query \yii\db\ActiveQuery */ $query = $this->baseModel->find(); $table_inheritance_joined = false; $dataProvider = new ActiveDataProvider(['query' => &$query, 'pagination' => ['pageSize' => 10], 'sort' => ['defaultOrder' => ['id' => SORT_DESC]]]); if (!$this->load($params)) { return $dataProvider; } $object = Object::getForClass($this->baseModel->className()); $baseModelTableName = $this->baseModel->tableName(); $eavJoinsCount = 0; $osvJoinsCount = 0; foreach ($this->propertyGroups as $groupId => $properties) { foreach ($properties as $key => $propertyValue) { /** @var \app\properties\PropertyValue $propertyValue */ $prop = Property::findById($propertyValue->property_id); if (empty($this->{$prop->key}) === true && $this->{$prop->key} !== '0') { continue; } // determine property storage type and join needed table if needed if ($prop->is_column_type_stored) { if ($table_inheritance_joined === false) { $table_inheritance_joined = true; $query->join('INNER JOIN', $object->column_properties_table_name . ' ti', 'ti.object_model_id = ' . $baseModelTableName . '.id'); } if ($prop->value_type === 'STRING' && $prop->property_handler_id !== 3) { $query->andFilterWhere(['like', 'ti.' . $prop->key, $this->{$prop->key}]); } else { $query->andFilterWhere(['ti.' . $prop->key => $this->{$prop->key}]); } } elseif ($prop->is_eav) { $eavJoinsCount++; $eavTableName = 'eav' . $eavJoinsCount; $key = 'key' . $eavJoinsCount; $query->join('INNER JOIN', "{$object->eav_table_name} {$eavTableName}", $eavTableName . '.object_model_id = ' . $baseModelTableName . ".id AND {$eavTableName}.key=:{$key}", [$key => $prop->key]); if ($prop->value_type === 'STRING' && $prop->property_handler_id !== 3) { $query->andFilterWhere(['like', $eavTableName . '.value', $this->{$prop->key}]); } else { // numeric - direct match $query->andFilterWhere([$eavTableName . '.value' => $this->{$prop->key}]); } } elseif ($prop->has_static_values) { $osvJoinsCount++; $osvTableName = 'osv' . $osvJoinsCount; $query->join('INNER JOIN', "object_static_values {$osvTableName}", "{$osvTableName}.object_id={$object->id} AND {$osvTableName}.object_model_id={$baseModelTableName}.id"); // numeric - direct match $query->andFilterWhere(["{$osvTableName}.property_static_value_id", $this->{$prop->key}]); } } } return $dataProvider; }
public static function tableName() { if (self::$_table) { return \Yii::$app->getDb()->tablePrefix . self::$_table; } return parent::tableName(); }
/** * @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; } }
/** * Get table name of SEO data table for ActiveRecord * @param ActiveRecord $activeRecord * @return string */ public static function tableName(ActiveRecord $activeRecord) { $tableName = $activeRecord->tableName(); if (substr($tableName, -2) == '}}') { return preg_replace('/{{(.+)}}/', '{{$1_' . self::$tableSuffix . '}}', $tableName); } else { return $tableName . '_' . self::$tableSuffix; } }
/** * @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); }
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; } }
/** * Store data record and track change statistics * * @param ActiveRecord $ActiveRecord * * @return bool false if not saved */ protected function storeDataRecord(ActiveRecord $ActiveRecord) { if ($ActiveRecord->getDirtyAttributes()) { $unsaved_record = clone $ActiveRecord; // Save record if (!$ActiveRecord->save()) { // Create error message $message = "Save error: " . json_encode($ActiveRecord->errors) . "\n"; $message .= "Record data: " . json_encode($ActiveRecord->getAttributes()) . "\n"; trigger_error($message, E_USER_WARNING); $this->incStat('error_' . $ActiveRecord->tableName()); return false; } // Store statistics if ($unsaved_record->isNewRecord) { $this->incStat('new_' . $ActiveRecord->tableName()); } else { $this->incStat('update_' . $ActiveRecord->tableName()); } } return true; }
public static function find() { $tenantTableName = '{{%tenant}}'; $field = ''; $model = parent::find(); if (parent::tableName() == $tenantTableName) { $field = '.id'; } else { $field = '.tenant_id'; } $model->where([parent::tableName() . $field => Yii::$app->session['tenant']]); return $model; }
/** * Returns a models primary-key in json format. This works also with * composite primary-keys * * @param \yii\db\ActiveRecord $model the model instance * @return string the models pk in json-format * @throws \yii\base\InvalidParamException if the model is not of type ActiveRecord * @throws \yii\base\InvalidConfigException if the models pk is empty or invalid */ public static function asJson($model) { //check if the model is valid if (!$model instanceof \yii\db\ActiveRecord) { throw new InvalidParamException(Yii::t('app', 'The model must be of type ActiveRecord')); } //fetch the models pk $pk = $model->primaryKey(); //assert that a valid pk was received if ($pk === null || !is_array($pk) || count($pk) == 0) { $msg = Yii::t('app', 'Invalid primary key definition: please provide a pk-definition for table {table}', ['table' => $model->tableName()]); throw new InvalidConfigException($msg); } //create final array and return it $arrPk = []; foreach ($pk as $pkCol) { $arrPk[$pkCol] = $model->{$pkCol}; } return Json::encode($arrPk); }
/** * @param ActiveRecord $model * @param array $changedAttributes */ public static function dropCaches($model, array $changedAttributes = []) { self::initialize(); $attrs = $model->getAttributes(); $changed = []; if ($changedAttributes) { $attrNames = array_keys($changedAttributes); foreach ($attrNames as $attrName) { if (array_key_exists($attrName, $attrs)) { $changed[$attrName] = $attrs[$attrName]; } } } $args = [$model->tableName(), json_encode($attrs, self::$jsonOptions), json_encode($changed, self::$jsonOptions)]; CacheHelper::evalSHA(self::$shaInvalidate, $args, 0); }
/** * @param integer $fileId * @return int * @throws Exception */ protected function updateOwner($fileId) { $this->owner->updateAttributes([$this->attribute => $fileId]); $sql = "\n UPDATE " . $this->owner->tableName() . "\n SET " . $this->attribute . " = :file\n WHERE id = :id\n "; return Yii::$app->db->createCommand($sql)->bindValue(':file', $fileId)->bindValue(':id', $this->owner->primaryKey)->execute(); }
/** * @inheritdoc */ public static function tableName() { return !empty(static::$tableName) ? static::$tableName : parent::tableName(); }
/** * @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); }
/** * Attaches the behavior object to the component. * The default implementation will set the [[owner]] property * and attach event handlers as declared in [[events]]. * Make sure you call the parent implementation if you override this method. * * @param Component $owner the component that this behavior is to be attached to. * * @throws InvalidConfigException */ public function attach($owner) { /** @var ActiveRecord $ownerClassName */ /** @var ActiveRecord $owner */ parent::attach($owner); $this->module = Yii::$app->getModule('language'); $this->currentLanguage = Yii::$app->language; foreach (LanguageHelper::getLanguages() as $language) { $this->availableLanguages[$language['code']] = $language['name']; } if (empty($this->availableLanguages) || !is_array($this->availableLanguages)) { throw new InvalidConfigException('Please specify at least one of available languages on ' . Url::to(['language/index']), 101); } if (array_values($this->availableLanguages) !== $this->availableLanguages) { $this->availableLanguages = array_keys($this->availableLanguages); } if (empty($this->attributes) || !is_array($this->attributes)) { throw new InvalidConfigException('Please specify multilingual attributes for the ' . get_class($this) . ' in the ' . get_class($this->owner), 103); } if (!$this->translateClassName) { if ($this->module->modelNamespace != null) { $this->translateClassName = $this->module->modelNamespace . '\\' . (new ReflectionClass($this->owner))->getShortName() . ucfirst($this->module->suffix); } else { $this->translateClassName = get_class($this->owner) . ucfirst($this->module->suffix); } } $this->ownerClassName = get_class($this->owner); $ownerClassName = $this->ownerClassName; $this->ownerPrimaryKey = $ownerClassName::primaryKey()[0]; if (!$this->translateForeignKey) { $this->translateForeignKey = $this->owner->tableName() . '_id'; } if (!$this->translateTableName) { $this->translateTableName = $this->owner->tableName() . '_' . $this->module->suffix; } $rules = $owner->rules(); $validators = $owner->getValidators(); foreach ($rules as $rule) { if ($rule[1] == 'unique') { continue; } $rule_attributes = is_array($rule[0]) ? $rule[0] : [$rule[0]]; $attributes = array_intersect($this->attributes, $rule_attributes); if (empty($attributes)) { continue; } $rule_attributes = []; foreach ($attributes as $key => $attribute) { foreach ($this->availableLanguages as $language) { $rule_attributes[] = $attribute . "_" . $language; } } $params = array_slice($rule, 2); if ($rule[1] !== 'required') { $validators[] = Validator::createValidator($rule[1], $owner, $rule_attributes, $params); } else { $validators[] = Validator::createValidator('safe', $owner, $rule_attributes, $params); } } if (class_exists($this->translateClassName)) { $translation = new $this->translateClassName(); foreach ($this->availableLanguages as $language) { foreach ($this->attributes as $attribute) { $this->setTranslateAttribute($attribute . "_" . $language, $translation->{$attribute}); if ($language == Yii::$app->language) { $this->setTranslateAttribute($attribute, $translation->{$attribute}); } } } } }
/** * 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; }
public function like($attribute) { $this->query->andFilterWhere(['like', $this->model->tableName() . '.' . $attribute, $this->model->{$attribute}]); }
/** * Returns a new ActiveQuery object. Can be overridden instead of getQuery(). * @param \yii\db\ActiveRecord $model * @return \yii\db\ActiveQuery */ protected function createQuery($model) { $query = $model::find(); if (empty($query->from)) { // required by the query authorizer behavior and when model implements ActiveSearchInterface $query->from = ['t' => $model->tableName()]; } return $query; }
/** * @param array $requestData * @throws BadRequestHttpException * @throws \Exception * @throws \yii\db\Exception */ protected function editAction($requestData) { $model = $this->model; if (!isset($requestData['id'])) { throw new BadRequestHttpException('Id param isn\'t set.'); } /** @var \yii\db\ActiveRecord $record */ if (($record = $model::findOne(['ROWID' => $requestData['id']])) === null) { return; } $relationColumns = []; $mcol = []; $mColVal = []; $i = 0; foreach ($this->columns as $column) { if (isset($requestData[$column])) { if (strpos($column, '.') === false) { // no relation $record->{$column} = $requestData[$column]; $mcol[$i] = $column; $mColVal[$i] = $requestData[$column]; } else { // with relation preg_match('/(.+)\\.([^\\.]+)/', $column, $matches); $relationColumns[$matches[1]][] = ['column' => $matches[2], 'value' => $requestData[$column]]; } $i++; } } $transaction = Yii::$app->db->beginTransaction(); $connection = \Yii::$app->db; try { if (count($relationColumns)) { foreach ($relationColumns as $relationName => $columns) { $relation = $record; foreach (explode('.', $relationName) as $relationPart) { $relation = $relation->{$relationPart}; if ($relation === null) { throw new BadRequestHttpException("Related model {$relationName} does not exist."); } } if (is_array($relation)) { throw new BadRequestHttpException('hasMany relation type isn\'t supported.'); } foreach ($columns as $column) { $relation->{$column}['column'] = $column['value']; } if (!$relation->save()) { $errors = ''; foreach ($relation->errors as $error) { $errors .= implode(' ', $error) . ' '; } $transaction->rollBack(); echo $errors; return; } } } /*$connection->createCommand() ->update($this->model->tableName(), [$mcol[1] => $mColVal[1]], ['ROWID' => $requestData['id']]) ->execute();*/ try { $connection->createCommand()->update($this->model->tableName(), [$mcol[1] => $mColVal[1]], ['ROWID' => $requestData['id']])->execute(); } catch (\yii\db\Exception $e) { throw new NotAcceptableHttpException('Policy not allowed.'); } /*if (!$record->save()) { $errors = ''; foreach ($record->errors as $error) { $errors .= (implode(' ', $error) . ' '); } $transaction->rollBack(); echo $errors; return; }*/ } catch (\Exception $e) { $transaction->rollBack(); throw $e; } $transaction->commit(); }
/** * Returns a value indicating whether the given active record is the same as the current one. * The comparison is made by comparing the table names and the primary key values of the two active records. * If one of the records [[isNewRecord|is new]] they are also considered not equal. * @param ActiveRecord $record record to compare to * @return boolean whether the two active records refer to the same row in the same database table. */ public function equals($record) { if ($this->isNewRecord || $record->isNewRecord) { return false; } return $this->tableName() === $record->tableName() && $this->getPrimaryKey() === $record->getPrimaryKey(); }
public static function tableName() { parent::tableName(); }