本文整理汇总了PHP中CActiveRecord::model方法的典型用法代码示例。如果您正苦于以下问题:PHP CActiveRecord::model方法的具体用法?PHP CActiveRecord::model怎么用?PHP CActiveRecord::model使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类CActiveRecord
的用法示例。
在下文中一共展示了CActiveRecord::model方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: update
/**
* @param CActiveRecord $model
* @param $sortableAttribute
* @param $sortOrderData
*
* @return string
*/
private function update($model, $sortableAttribute, $sortOrderData)
{
$pk = $model->tableSchema->primaryKey;
$pk_array = array();
if (is_array($pk)) {
// composite key
$string_ids = array_keys($sortOrderData);
$array_ids = array();
foreach ($string_ids as $string_id) {
$array_ids[] = explode(',', $string_id);
}
foreach ($array_ids as $array_id) {
$pk_array[] = array_combine($pk, $array_id);
}
} else {
// normal key
$pk_array = array_keys($sortOrderData);
}
$models = $model->model()->findAllByPk($pk_array);
$transaction = Yii::app()->db->beginTransaction();
try {
foreach ($models as $model) {
$_key = is_array($pk) ? implode(',', array_values($model->primaryKey)) : $model->primaryKey;
$model->{$sortableAttribute} = $sortOrderData[$_key];
$model->save();
}
$transaction->commit();
} catch (Exception $e) {
// an exception is raised if a query fails
$transaction->rollback();
}
}
示例2: run
public function run($action, $to, $id)
{
$to = CActiveRecord::model($this->getController()->CQtreeGreedView['modelClassName'])->findByPk((int) $to);
$moved = CActiveRecord::model($this->getController()->CQtreeGreedView['modelClassName'])->findByPk((int) $id);
if (!is_null($to) && !is_null($moved)) {
try {
switch ($action) {
case 'child':
$moved->moveAsLast($to);
break;
case 'before':
if ($to->isRoot()) {
$moved->moveAsRoot();
} else {
$moved->moveBefore($to);
}
break;
case 'after':
if ($to->isRoot()) {
$moved->moveAsRoot();
} else {
$moved->moveAfter($to);
}
break;
}
} catch (Exception $e) {
Yii::app()->user->setFlash('CQTeeGridView', $e->getMessage());
}
}
$this->getController()->redirect(array($this->getController()->CQtreeGreedView['adminAction']));
}
示例3: getModelInstance
/**
* @return CActiveRecord
*/
private function getModelInstance()
{
if (!isset($this->commentModelClass)) {
throw new CException(Yii::t('yiiext', 'commentModelClass should be defined.'));
}
return CActiveRecord::model($this->commentModelClass);
}
示例4: model
/**
* Returns the static model of the specified AR class.
*
* @param string $className
* @return YdActiveRecord the static model class
*/
public static function model($className = null)
{
if (!$className) {
$className = get_called_class();
}
return parent::model($className);
}
示例5: validateModel
public function validateModel($attribute, $params)
{
if ($this->hasErrors('model')) {
return;
}
$class = @Yii::import($this->model, true);
if (!is_string($class) || !$this->classExists($class)) {
$this->addError('model', "Class '{$this->model}' does not exist or has syntax error.");
} else {
if (!is_subclass_of($class, 'CActiveRecord')) {
$this->addError('model', "'{$this->model}' must extend from CActiveRecord.");
} else {
$table = CActiveRecord::model($class)->tableSchema;
if ($table->primaryKey === null) {
$this->addError('model', "Table '{$table->name}' does not have a primary key.");
} else {
if (is_array($table->primaryKey)) {
$this->addError('model', "Table '{$table->name}' has a composite primary key which is not supported by crud generator.");
} else {
$this->_modelClass = $class;
$this->_table = $table;
}
}
}
}
}
示例6: validateCompositeUniqueKeys
/**
* Validates composite unique keys
*/
public function validateCompositeUniqueKeys()
{
$this->_normalizeKeysData();
$object = $this->getOwner();
foreach ($this->uniqueKeys as $uk) {
// check whether validation of the current key should be skipped
foreach ($uk['skipOnErrorIn'] as $skipAttr) {
if ($object->getError($skipAttr)) {
continue 2;
}
}
$criteria = new CDbCriteria();
foreach ($uk['attributes'] as $attr) {
if ($object->{$attr} === null) {
$criteria->addCondition("`{$attr}`" . ' is null');
} else {
$criteria->compare("`{$attr}`", $object->{$attr});
}
}
/*
* if the model is a new record or if it's an old record with modified unique key value
* then the composite key should be unique ($criteriaLimit = 0)
*
* if we are updating an existing record without changes of unique key attributes
* then we should allow one existing record satisfying the criteria
*/
$ukIsChanged = !$object->isNewRecord && $uk['oldValue'] != $this->_getUkValue($uk['attributes']);
$criteriaLimit = $object->isNewRecord || $ukIsChanged ? 0 : 1;
if (CActiveRecord::model(get_class($object))->count($criteria) > $criteriaLimit) {
foreach ($uk['errorAttributes'] as $attr) {
$object->addError($attr, $uk['errorMessage']);
}
}
}
}
示例7: run
public function run($id = false, $model = false, $forceDelete = false)
{
$modelName = $this->model && is_string($this->model) ? $this->model : (request()->getParam('model') ? request()->getParam('model') : $this->controller->model);
if ($id) {
//delete one model
$result = $this->controller->loadModel($modelName, $id)->delete();
if (!request()->isAjaxRequest && $result) {
$this->controller->redirect(user()->gridIndex);
}
Common::jsonSuccess(true);
} else {
$items = Common::getChecked('items');
if ($items) {
if (!$forceDelete) {
foreach ($items as $id) {
$this->controller->loadModel($modelName, $id)->delete();
}
} else {
$criteria = new SDbCriteria();
$criteria->compare('id', $items);
CActiveRecord::model($modelName)->deleteAll($criteria);
}
Common::jsonSuccess(true);
}
}
Common::jsonError("Ошибка");
}
示例8: suggestIdentifier
public function suggestIdentifier($model)
{
if (!$model instanceof CActiveRecord) {
$model = CActiveRecord::model(Yii::import($model));
}
if (is_callable(array($model, 'getItemLabel'))) {
return 'itemLabel';
}
$nonNumericFound = false;
$columns = $model->tableSchema->columns;
foreach ($columns as $column) {
if ($column->isPrimaryKey) {
$fallbackName = $column->name;
}
// Use the first non-numeric column as a fallback
if (!$column->isForeignKey && !$column->isPrimaryKey && $column->type != 'BIGINT' && $column->type != 'INT' && $column->type != 'INTEGER' && $column->type != 'BOOLEAN' && !$nonNumericFound) {
$fallbackName = $column->name;
$nonNumericFound = true;
}
// Return the first title, name, label column, if found
if (in_array($column->name, array("title", "name", "label"))) {
$fallbackName = $column->name;
break;
}
}
return $fallbackName;
}
示例9: generateValueField
/**
* @param CActiveRecord $modelClass
* @param CDbColumnSchema $column
*/
public function generateValueField($modelClass, $column, $view = false)
{
if ($column->isForeignKey) {
$model = CActiveRecord::model($modelClass);
$table = $model->getTableSchema();
$fk = $table->foreignKeys[$column->name];
$fmodel = CActiveRecord::model(ucfirst($fk[0]));
$modelTable = ucfirst($fmodel->tableName());
$fcolumns = $fmodel->attributeNames();
//$rel = $model->getActiveRelation($column->name);
$relname = strtolower($fk[0]);
foreach ($model->relations() as $key => $value) {
if (strcasecmp($value[2], $column->name) == 0) {
$relname = $key;
}
}
//return("\$model->{$relname}->{$fcolumns[1]}");
//return("CHtml::value(\$model,\"{$relname}.{$fcolumns[1]}\")");
//return("{$relname}.{$fcolumns[1]}");
if ($view) {
return "\n\t\t\t\t\tarray(\n\t\t\t\t\t\t\t'name'=>'{$column->name}',\n\t\t\t\t\t\t\t'value'=>CHtml::value(\$model,'{$relname}.{$fcolumns[1]}'),\n\t\t\t\t\t\t\t)\n\t\t\t\t\t";
} else {
return "\n\t\t\t\t\tarray(\n\t\t\t\t\t\t\t'name'=>'{$column->name}',\n\t\t\t\t\t\t\t'value'=>'\$data->{$relname}->{$fcolumns[1]}',\n\t\t\t\t\t\t\t'filter'=>CHtml::listData({$modelTable}::model()->findAll(), '{$fcolumns[0]}', '{$fcolumns[1]}'),\n\t\t\t\t\t\t\t)\n\t\t\t\t\t";
}
//{$relname}.{$fcolumns[1]}
} elseif (strtoupper($column->dbType) == 'BOOLEAN' or strtoupper($column->dbType) == 'TINYINT(1)' or strtoupper($column->dbType) == 'BIT') {
if ($view) {
return "\n\t\t\t\t\tarray(\n\t\t\t\t\t\t\t'name'=>'{$column->name}',\n\t\t\t\t\t\t\t'value'=>\$model->{$column->name}?Yii::t('app', 'Yes'):Yii::t('app', 'No'),\n\t\t\t\t\t\t\t)\n\t\t\t\t\t";
} else {
return "\n\t\t\t\t\tarray(\n\t\t\t\t\t\t\t'name'=>'{$column->name}',\n\t\t\t\t\t\t\t'value'=>'\$data->{$column->name}?Yii::t('app','Yes'):Yii::t('app', 'No')',\n\t\t\t\t\t\t\t\t'filter'=>array('0'=>Yii::t('app','No'),'1'=>Yii::t('app','Yes')),\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t";
}
} else {
return "'" . $column->name . "'";
}
}
示例10: actionIndex
/**
* This is the default 'index' action that is invoked
* when an action is not explicitly requested by users.
*/
public function actionIndex()
{
$buscar = new BuscarPeliculaForm();
if (isset($_POST['BuscarPeliculaForm'])) {
$buscar->attributes = $_POST['BuscarPeliculaForm'];
if ($buscar->validate()) {
// Hacer consulta y redireccionar con resultados
switch ($buscar->param) {
case "titulo":
$peliculas = CActiveRecord::model("Pelicula")->findAll('titulo LIKE "%' . $buscar->value . '%"');
break;
case "agno":
$peliculas = CActiveRecord::model("Pelicula")->findAll('agno LIKE "%' . $buscar->value . '%"');
break;
}
$this->render('index', array("msg" => "Busco " . $buscar->value . " por " . $buscar->param, "peliculas" => $peliculas, "buscar" => $buscar));
} else {
$peliculas = CActiveRecord::model("Pelicula")->findAll();
$this->render('index', array("msg" => "Ultimas añadidas", "peliculas" => $peliculas, "buscar" => $buscar));
}
} else {
$peliculas = CActiveRecord::model("Pelicula")->findAll();
$this->render('index', array("msg" => "Ultimas añadidas", "peliculas" => $peliculas, "buscar" => $buscar));
}
}
示例11: testTags
public function testTags()
{
$model = $this->newModel();
$tags = array('#this', '#that');
// Test adding:
// ob_start();
$realModel = $this->contacts('testAnyone');
$response = $model->addTags('Contacts', $realModel->id, $tags);
$tagTable = CActiveRecord::model('Tags')->tableName();
$tagsOnServer = Yii::app()->db->createCommand()->select('tag')->from($tagTable)->where('itemId=:itemId AND type=:itemType', array(':itemId' => $realModel->id, ':itemType' => get_class($realModel)))->queryColumn();
// var_dump($tags);
// var_dump($tagsOnServer);
// print_r(json_decode($response,1));
$tagsNotAdded = array_diff($tags, $tagsOnServer);
$this->assertEmpty($tagsNotAdded, 'Failed asserting that tags were saved on the server.');
// Test getting:
$tagsFromServer = $model->getTags('Contacts', $this->contacts('testAnyone')->id);
// ob_end_clean();
// var_dump($tagsFromServer);
// var_dump($tagsOnServer);
$tagsNotRetrieved = array_diff($tagsOnServer, $tagsFromServer);
$this->assertEmpty($tagsNotRetrieved, 'Failed asserting that all tags were properly retrieved.');
// Test deleting:
$response = $model->removeTag('Contacts', $this->contacts('testAnyone')->id, '#this');
$tagsOnServer = Yii::app()->db->createCommand()->select('tag')->from($tagTable)->where('itemId=:itemId AND type=:itemType', array(':itemId' => $realModel->id, ':itemType' => get_class($realModel)))->queryColumn();
$tagsDeleted = array_diff($tags, $tagsOnServer);
// var_dump($response);
// var_dump($tagsDeleted);
$this->assertEquals(1, count($tagsDeleted), 'Failed asserting that one and only one tag was deleted.');
$this->assertEquals('#this', $tagsDeleted[0], 'Failed asserting that the right tag got deleted.');
}
示例12: actionIndex
public function actionIndex()
{
$criteria = $this->getIndexCriteria();
$dataProvider = new CActiveDataProvider($this->getModelClass(), array('criteria' => $criteria, 'pagination' => array('pageSize' => $this->getPagesize(), 'pageVar' => 'page')));
list($downloadSum, $totalPriceSum) = CActiveRecord::model($this->getModelClass())->sum(array('download_number', 'total_price'), $criteria);
/*模糊搜索start*/
$filter = $this->getFilterCondition();
$cp_id = $filter['cp_id'];
$adv_id = $filter['adv_id'];
/*获得满足$cp_id的Advertise 10-28*/
$cpadv = new CDbCriteria();
$cpadv->order = 'id ASC';
$cpadv->compare('cp_id', $cp_id);
$advertises = Advertise::model()->findAll($cpadv);
/*获得满足$adv_id的Channel 10-28*/
$criteria = new CDbCriteria();
$criteria->select = "channel_id";
$criteria->order = "channel_id asc";
$criteria->compare('adv_id', $adv_id);
$criteria->distinct = true;
$advtertises = AdvertiseChannel::model()->findAll($criteria);
$i = 0;
foreach ($advtertises as $a) {
$arr[$i] = $a->channel->id;
$i++;
}
$criter = new CDbCriteria();
$criter->addInCondition('id', $arr);
$criter->order = "name desc";
$criter->distinct = true;
$channels = Channel::model()->findAll($criter);
/*10-28 end*/
$this->render('/report/index', array('downloadSum' => $downloadSum ? $downloadSum : '0', 'totalPriceSum' => $totalPriceSum ? $totalPriceSum : '0.00', 'dataProvider' => $dataProvider, 'filter' => $filter, 'cp' => CP::model()->findAll(), 'advertises' => $advertises, 'channels' => $channels, 'attributes' => $this->getAdminAttributes()));
}
示例13: validateAttribute
protected function validateAttribute($object, $attribute)
{
$value = $object->{$attribute};
if ($this->allowEmpty && $this->isEmpty($value)) {
return;
}
$className = $this->className === null ? get_class($object) : Yii::import($this->className);
$attributeName = $this->attributeName === null ? $attribute : $this->attributeName;
$finder = CActiveRecord::model($className);
$table = $finder->getTableSchema();
if (!is_array($attributeName)) {
$attributeName = array($attributeName);
}
$condition = array();
foreach ($attributeName as $aN) {
if (($column = $table->getColumn($aN)) === null) {
throw new CException(Yii::t('yii', 'Table "{table}" does not have a column named "{column}".', array('{column}' => $aN, '{table}' => $table->name)));
}
$condition[] = $column->rawName . '=:vp';
}
$criteria = array('condition' => implode(' OR ', $condition), 'params' => array(':vp' => $value));
if ($this->criteria !== array()) {
$criteria = new CDbCriteria($criteria);
$criteria->mergeWith($this->criteria);
}
if (!$finder->exists($criteria)) {
$message = $this->message !== null ? $this->message : Yii::t('yii', '{attribute} "{value}" is invalid.');
$this->addError($object, $attribute, $message, array('{value}' => $value));
}
}
示例14: authenticate
/**
* Authentication
* @return bool
*/
public function authenticate()
{
/** @var AccountModule $account */
$account = Yii::app()->getModule('account');
/** @var AccountUser $user */
$user = CActiveRecord::model($account->userClass)->find('(LOWER(username)=? OR LOWER(email)=?)', array(strtolower($this->username), strtolower($this->username)));
if (!$user) {
$this->errorCode = self::ERROR_USERNAME_INVALID;
return false;
}
if ($account->activatedField && !$user->{$account->activatedField}) {
$this->errorCode = self::ERROR_NOT_ACTIVATED;
return false;
}
if ($account->disabledField && $user->{$account->disabledField}) {
$this->errorCode = self::ERROR_DISABLED;
return false;
}
if (!$this->skipPassword && !CPasswordHelper::verifyPassword($this->password, $user->{$account->passwordField})) {
$this->errorCode = self::ERROR_PASSWORD_INVALID;
return false;
}
$this->_id = $user->primaryKey;
$this->username = $account->usernameField && $user->{$account->usernameField} ? $user->{$account->usernameField} : $user->{$account->emailField};
$this->errorCode = self::ERROR_NONE;
return true;
}
示例15: validateAttribute
/**
* @param CModel $object the object being validated
* @param string $attribute if there is an validation error then error message
* will be added to this property
*/
protected function validateAttribute($object, $attribute)
{
$class = get_class($object);
Yii::import($class);
$keyColumns = explode(',', $this->keyColumns);
if (count($keyColumns) == 1) {
throw new CException('CUniqueValidator should be used instead');
}
$columnsLabels = $object->attributeLabels();
$criteria = new CDbCriteria();
$keyColumnsLabels = array();
foreach ($keyColumns as &$column) {
$column = trim($column);
$criteria->compare($column, $object->{$column});
$keyColumnsLabels[] = $columnsLabels[$column];
}
unset($column);
$criteria->limit = 1;
if (CActiveRecord::model($class)->count($criteria)) {
$message = Yii::t('yii', $this->errorMessage, array('{columns_labels}' => join(', ', $keyColumnsLabels)));
if ($this->addErrorToAllColumns) {
foreach ($keyColumns as $column) {
$this->addError($object, $column, $message);
}
} else {
$this->addError($object, $attribute, $message);
}
}
}