• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

PHP CActiveRecord类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了PHP中CActiveRecord的典型用法代码示例。如果您正苦于以下问题:PHP CActiveRecord类的具体用法?PHP CActiveRecord怎么用?PHP CActiveRecord使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了CActiveRecord类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的PHP代码示例。

示例1: save

 public function save()
 {
     parent::save();
     /**
      * У сотрудников, которых нет приказов по
      * ГАК в году комиссии автоматически устанавливается
      * приказ от комиссии
      */
     if ($this->order_id !== 0) {
         $persons = new CArrayList();
         foreach ($this->members->getItems() as $person) {
             $persons->add($person->getId(), $person);
         }
         if (!is_null($this->manager)) {
             $persons->add($this->manager->getId(), $this->manager);
         }
         foreach ($persons->getItems() as $person) {
             if (is_null($person->getSABOrdersByYear($this->year))) {
                 $ar = new CActiveRecord(array("id" => null, "person_id" => $person->getId(), "year_id" => $this->year->getId(), "order_id" => $this->order_id));
                 $ar->setTable(TABLE_SAB_PERSON_ORDERS);
                 $ar->insert();
             }
         }
     }
 }
开发者ID:Rustam44,项目名称:ASUPortalPHP,代码行数:25,代码来源:CSABCommission.class.php


示例2: attach

 /**
  * @param CActiveRecord $owner
  */
 public function attach($owner)
 {
     $validator = new yupe\components\validators\NumberValidator();
     $validator->attributes = array($this->priceAttribute, $this->priceEurAttribute, $this->priceOldAttribute);
     $owner->getValidatorList()->add($validator);
     parent::attach($owner);
 }
开发者ID:kuzmina-mariya,项目名称:unizaro-decor,代码行数:10,代码来源:PriceBehavior.php


示例3: 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();
     }
 }
开发者ID:zhaoyan158567,项目名称:YiiBooster,代码行数:39,代码来源:TbSortableAction.php


示例4: save

 public function save()
 {
     $this->grant->save();
     /**
      * Работа с участниками
      */
     $members = array();
     if (array_key_exists("members", $this->_fields)) {
         $members = $this->_fields["members"];
     }
     /**
      * Делаем руководителя тоже участником
      */
     if ($this->grant->manager_id != "0") {
         $members[] = $this->grant->manager_id;
     }
     /**
      * Удаляем старых участников
      */
     foreach (CActiveRecordProvider::getWithCondition(TABLE_GRANT_MEMBERS, "grant_id= " . $this->grant->getId())->getItems() as $ar) {
         $ar->remove();
     }
     /**
      * Добавляем новых
      */
     foreach ($members as $member) {
         $ar = new CActiveRecord(array("id" => null, "grant_id" => $this->grant->getId(), "person_id" => $member));
         $ar->setTable(TABLE_GRANT_MEMBERS);
         $ar->insert();
     }
 }
开发者ID:Rustam44,项目名称:ASUPortalPHP,代码行数:31,代码来源:CGrantForm.class.php


示例5: save

 public function save()
 {
     $group = $this->group;
     $roles = array();
     if (array_key_exists("roles", $group)) {
         $roles = $group["roles"];
         unset($group["roles"]);
     }
     $groupObj = new CUserGroup();
     $groupObj->setAttributes($group);
     /**
      * Удаляем старые задачи группы и пользователей
      */
     foreach (CActiveRecordProvider::getWithCondition(TABLE_USER_GROUP_HAS_ROLES, "user_group_id = " . $groupObj->getId())->getItems() as $ar) {
         $ar->remove();
     }
     $groupObj->save();
     /**
      * Создаем новые задачи группы и пользователей
      */
     foreach ($roles as $role => $level) {
         if ($level != 0) {
             $ar = new CActiveRecord(array("id" => null, "user_group_id" => $groupObj->getId(), "task_id" => $role, "task_rights_id" => $level));
             $ar->setTable(TABLE_USER_GROUP_HAS_ROLES);
             $ar->insert();
         }
     }
 }
开发者ID:Rustam44,项目名称:ASUPortalPHP,代码行数:28,代码来源:CUserGroupForm.class.php


示例6: attach

 /**
  * @param CActiveRecord $owner
  */
 public function attach($owner)
 {
     $validator = new CSafeValidator();
     $validator->attributes = array($this->attribute);
     $owner->getValidatorList()->add($validator);
     parent::attach($owner);
 }
开发者ID:kuzmina-mariya,项目名称:gallery,代码行数:10,代码来源:DMultiplyListBehavior.php


示例7: 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']));
 }
开发者ID:kostya1017,项目名称:our,代码行数:31,代码来源:MoveNode.php


示例8: assertSaves

 /**
  * Assert thet the model can be saved without error and, if errors are present, print
  * out the corresponding error messages.
  * @param CActiveRecord $model
  */
 public function assertSaves(CActiveRecord $model)
 {
     $saved = $model->save();
     if ($model->hasErrors()) {
         VERBOSE_MODE && print_r($model->getErrors());
     }
     $this->assertTrue($saved);
 }
开发者ID:keyeMyria,项目名称:CRM,代码行数:13,代码来源:X2TestCase.php


示例9: usernameFieldsSet

 /**
  * Sets username fields of a model
  */
 public static function usernameFieldsSet(CActiveRecord $model, $username)
 {
     if ($model->hasAttribute('updatedBy')) {
         $model->updatedBy = $username;
     }
     if ($model->hasAttribute('createdBy') && $model->isNewRecord) {
         $model->createdBy = $username;
     }
 }
开发者ID:dsyman2,项目名称:X2CRM,代码行数:12,代码来源:X2ChangeLogBehavior.php


示例10: saveFromPost

 /**
  * Attempts to save the specified model with attribute values from POST. If 
  * the saving fails or if no POST data is available it returns false.
  * @param CActiveRecord $model the model
  * @return boolean whether the model was saved
  */
 protected function saveFromPost(&$model)
 {
     if (isset($_POST[$this->getModelClass()])) {
         $model->attributes = $_POST[$this->getModelClass()];
         if ($model->save()) {
             return true;
         }
     }
     return false;
 }
开发者ID:pweisenburger,项目名称:xbmc-video-server,代码行数:16,代码来源:ModelController.php


示例11: saveActiveRecord

 public function saveActiveRecord(CActiveRecord $record)
 {
     try {
         if (!$record->save()) {
             new \Error(5, null, json_encode($record->getErrors()));
         }
     } catch (Exception $e) {
         new \Error(5, null, $e->getMesaage());
     }
 }
开发者ID:Yougmark,项目名称:TiCheck_Server,代码行数:10,代码来源:ModifyController.php


示例12: unSubscribe

 /**
  * @param \CActiveRecord $model
  *
  * @return bool
  */
 public function unSubscribe(\CActiveRecord $model)
 {
     try {
         if ($channel = $this->getChannel()) {
             return $channel->unSubscribe($model->getSubscriber());
         }
     } catch (\CException $e) {
     }
     return false;
 }
开发者ID:sim2github,项目名称:yii-node-socket,代码行数:15,代码来源:ArChannel.php


示例13: format

 /**
  * {@inheritDoc}
  * @see IExportFormat::format()
  */
 public function format(CActiveRecord $record, array $data, array $templates = array())
 {
     if (empty($data)) {
         throw new CDbException(Yii::t('yii', 'Can not generate multiple insert command with empty data set.'));
     }
     $templates = array_merge(array('main' => "INSERT INTO {{tableName}} ({{columnInsertNames}}) VALUES \n{{rowInsertValues}};\n", 'columnInsertValue' => '{{value}}', 'columnInsertValueGlue' => ', ', 'rowInsertValue' => '({{columnInsertValues}})', 'rowInsertValueGlue' => ",\n", 'columnInsertNameGlue' => ', '), $templates);
     $table = $record->tableSchema;
     if ($table === null) {
         throw new CDbException(Yii::t('yii', 'Table "{table}" does not exist.', array('{table}' => $record->tableName())));
     }
     $tableName = $table->rawName;
     $columns = array();
     foreach ($data as $rowData) {
         foreach ($rowData as $columnName => $columnValue) {
             if (!in_array($columnName, $columns, true)) {
                 if ($table->getColumn($columnName) !== null) {
                     $columns[] = $columnName;
                 }
             }
         }
     }
     $columnInsertNames = array();
     foreach ($columns as $name) {
         $columnInsertNames[$name] = $record->getDbConnection()->quoteColumnName($name);
     }
     $columnInsertNamesSqlPart = implode($templates['columnInsertNameGlue'], $columnInsertNames);
     $rowInsertValues = array();
     foreach ($data as $rowData) {
         $columnInsertValues = array();
         foreach ($columns as $columnName) {
             /* @var $column CDbColumnSchema */
             $column = $table->getColumn($columnName);
             $columnValue = array_key_exists($columnName, $rowData) ? $rowData[$columnName] : new CDbException('NULL');
             if ($columnValue instanceof CDbExpression) {
                 $columnInsertValue = $columnValue->expression;
                 // in reverse order to prevent precocious replacements on param values
                 foreach (array_reverse($columnValue->params) as $columnValueParamName => $columnValueParam) {
                     $secureColumnParamValue = $this->secureOutput($record->getDbConnection(), $columnValueParam);
                     $columnInsertValue = strtr(':' . $columnValueParamName, $secureColumnParamValue, $columnInsertValue);
                 }
             } else {
                 $columnInsertValue = $column->typecast($columnValue);
                 if ($columnInsertValue === '' && $column->allowNull) {
                     $columnInsertValue = null;
                 }
                 $columnInsertValue = $this->secureOutput($record->getDbConnection(), $columnInsertValue);
             }
             $columnInsertValues[] = strtr($templates['columnInsertValue'], array('{{column}}' => $columnInsertNames[$columnName], '{{value}}' => $columnInsertValue));
         }
         $rowInsertValues[] = strtr($templates['rowInsertValue'], array('{{tableName}}' => $tableName, '{{columnInsertNames}}' => $columnInsertNamesSqlPart, '{{columnInsertValues}}' => implode($templates['columnInsertValueGlue'], $columnInsertValues)));
     }
     $sql = strtr($templates['main'], array('{{tableName}}' => $tableName, '{{columnInsertNames}}' => $columnInsertNamesSqlPart, '{{rowInsertValues}}' => implode($templates['rowInsertValueGlue'], $rowInsertValues)));
     return $sql;
 }
开发者ID:anastaszor,项目名称:yii1-export,代码行数:58,代码来源:SqlExportFormat.php


示例14: listData

 /**
  * @param CActiveRecord $model
  * @param string $valueField defaults to primary key field
  * @param string $textField defaults to primary key field
  * @return array
  */
 public static function listData($model, $valueField = '', $textField = '')
 {
     $pk = $model->metaData->tableSchema->primaryKey;
     if ($valueField === '') {
         $valueField = $pk;
     }
     if ($textField === '') {
         $textField = $valueField;
     }
     return CHtml::listData($model->findAll(array('select' => $valueField == $textField ? $valueField : $valueField . ',' . $textField)), $valueField, $textField);
 }
开发者ID:DarkAiR,项目名称:test,代码行数:17,代码来源:EHtml.php


示例15: checkUpdatedAtField

 /**
  * @param CActiveRecord $record
  * @param string        $colName
  * @param string        $newValue
  */
 protected function checkUpdatedAtField(CActiveRecord $record, $colName = 'name', $newValue = 'xxxxx')
 {
     $oldColumnValue = $record->{$colName};
     // Modifier l'objet met le champ updated_at à jour
     $oldUpdatedAt = $record->updated_at;
     $record->{$colName} = $newValue;
     $this->assertTrue($record->save());
     $this->assertNotEquals($oldUpdatedAt, $record->updated_at);
     // restauration de la valeur de départ
     $record->{$colName} = $oldColumnValue;
     $this->assertTrue($record->save());
 }
开发者ID:ChristopheBrun,项目名称:hLib,代码行数:17,代码来源:DbTestCase.php


示例16: Model2ArrayRec

 /**
  * @param CActiveRecord $model
  * */
 private static function Model2ArrayRec($model)
 {
     $data = $model->attributes;
     //Levantando relacionamentos
     $rels = $model->relations();
     foreach ($rels as $relation => $params) {
         //Irá gerar um vetor com todos os relacionamentos
         if ($model->hasRelated($relation)) {
             $data[$relation] = self::relations2Array($model, $relation);
         }
     }
     return $data;
 }
开发者ID:bruno-melo,项目名称:components,代码行数:16,代码来源:Webservice.php


示例17: getViewAttributesEntry

 /**
  * Renvoie une ligne à insérer dans le tableau 'attributes' d'un widget de type CDetailView, CGridView...
  * Le formatage varie selon le type de la colonne $column
  * @param CDbColumnSchema $column
  * @param CActiveRecord   $templateRecord
  * @return string
  */
 public static function getViewAttributesEntry(CDbColumnSchema $column, CActiveRecord $templateRecord)
 {
     switch ($column->dbType) {
         case 'date':
             $out = "{$column->name}:date:" . $templateRecord->getAttributeLabel($column->name);
             break;
         case 'datetime':
             $out = "{$column->name}:datetime:" . $templateRecord->getAttributeLabel($column->name);
             break;
         default:
             $out = $column->name;
     }
     return $out;
 }
开发者ID:ChristopheBrun,项目名称:hLib,代码行数:21,代码来源:CodeGeneratorHelper.php


示例18: actionUser

 /**
  * Displays the authorization assignments for an user.
  */
 public function actionUser()
 {
     // Create the user model and attach the required behavior
     $userClass = $this->module->userClass;
     $model = CActiveRecord::model($userClass)->findByPk($_GET['id']);
     $this->_authorizer->attachUserBehavior($model);
     $assignedItems = $this->_authorizer->getAuthItems(null, $model->getId());
     $assignments = array_keys($assignedItems);
     // Make sure we have items to be selected
     $assignSelectOptions = Rights::getAuthItemSelectOptions(null, $assignments);
     if ($assignSelectOptions !== array()) {
         $formModel = new AssignmentForm();
         // Form is submitted and data is valid, redirect the user
         if (isset($_POST['AssignmentForm']) === true) {
             $formModel->attributes = $_POST['AssignmentForm'];
             if ($formModel->validate() === true) {
                 // Update and redirect
                 $this->_authorizer->authManager->assign($formModel->itemname, $model->getId());
                 $item = $this->_authorizer->authManager->getAuthItem($formModel->itemname);
                 $item = $this->_authorizer->attachAuthItemBehavior($item);
                 Yii::app()->user->setFlash($this->module->flashSuccessKey, Rights::t('core', 'Permission :name assigned.', array(':name' => $item->getNameText())));
                 $this->redirect(array('assignment/user', 'id' => $model->getId()));
             }
         }
     } else {
         $formModel = null;
     }
     // Create a data provider for listing the assignments
     $dataProvider = new RAuthItemDataProvider('assignments', array('userId' => $model->getId()));
     // Render the view
     $this->render('user', array('model' => $model, 'dataProvider' => $dataProvider, 'formModel' => $formModel, 'assignSelectOptions' => $assignSelectOptions));
 }
开发者ID:sharmarakesh,项目名称:edusec-college-management-system,代码行数:35,代码来源:AssignmentController.php


示例19: 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;
                 }
             }
         }
     }
 }
开发者ID:israelCanul,项目名称:Bonanza_V2,代码行数:26,代码来源:CrudCode.php


示例20: setUp

 public function setUp()
 {
     if (!extension_loaded('pdo') || !extension_loaded('pdo_pgsql')) {
         $this->markTestSkipped('PDO and PostgreSQL extensions are required.');
     }
     $this->db = new CDbConnection('pgsql:host=127.0.0.1;dbname=yii', 'test', 'test');
     try {
         $this->db->active = true;
     } catch (Exception $e) {
         $schemaFile = realpath(dirname(__FILE__) . '/../data/postgres.sql');
         $this->markTestSkipped("Please read {$schemaFile} for details on setting up the test environment for PostgreSQL test case.");
     }
     try {
         $this->db->createCommand('DROP SCHEMA test CASCADE')->execute();
     } catch (Exception $e) {
     }
     try {
         $this->db->createCommand('DROP TABLE yii_types CASCADE')->execute();
     } catch (Exception $e) {
     }
     $sqls = file_get_contents(dirname(__FILE__) . '/../data/postgres.sql');
     foreach (explode(';', $sqls) as $sql) {
         if (trim($sql) !== '') {
             $this->db->createCommand($sql)->execute();
         }
     }
     $this->db->active = false;
     $config = array('basePath' => dirname(__FILE__), 'components' => array('db' => array('class' => 'system.db.CDbConnection', 'connectionString' => 'pgsql:host=127.0.0.1;dbname=yii', 'username' => 'test', 'password' => 'test')));
     $app = new TestApplication($config);
     $app->db->active = true;
     CActiveRecord::$db = $this->db = $app->db;
 }
开发者ID:nailgg,项目名称:yii,代码行数:32,代码来源:CActiveRecord2Test.php



注:本文中的CActiveRecord类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
PHP CActiveRecordBehavior类代码示例发布时间:2022-05-23
下一篇:
PHP CActiveForm类代码示例发布时间:2022-05-23
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap