postgres не работает $model->id в actionCreate
Добавлено: 2015.07.03, 17:53
не могу использовать $model->id в actionCreate. настройки gii по дефолту. подскажите это баг или я просто не умею готовить?
Форум Yii-программистов
https://yiiframework.ru/forum/
Код: Выделить всё
CREATE TABLE techbase.item (
id SERIAL,
name TEXT NOT NULL,
url TEXT,
CONSTRAINT item_pkey PRIMARY KEY(id),
CONSTRAINT item_url_key UNIQUE(url)
)
WITH (oids = false);
COMMENT ON COLUMN techbase.item.id
IS 'ид';
COMMENT ON COLUMN techbase.item.name
IS 'имя';
COMMENT ON COLUMN techbase.item.url
IS 'Источник (URL без http://)';
Код: Выделить всё
<?php
/**
* This is the model class for table "item".
*
* The followings are the available columns in table 'item':
* @property integer $id
* @property string $name
* @property string $url
*/
class Item extends CActiveRecord
{
/**
* @return string the associated database table name
*/
public function tableName()
{
return 'item';
}
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('name', 'required'),
array('url', 'safe'),
// The following rule is used by search().
// @todo Please remove those attributes that should not be searched.
array('id, name, url', 'safe', 'on'=>'search'),
);
}
/**
* @return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
);
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'id' => 'ид',
'name' => 'имя',
'url' => 'Источник (URL без http://)',
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
*
* Typical usecase:
* - Initialize the model fields with values from filter form.
* - Execute this method to get CActiveDataProvider instance which will filter
* models according to data in model fields.
* - Pass data provider to CGridView, CListView or any similar widget.
*
* @return CActiveDataProvider the data provider that can return the models
* based on the search/filter conditions.
*/
public function search()
{
// @todo Please modify the following code to remove attributes that should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('id',$this->id);
$criteria->compare('name',$this->name,true);
$criteria->compare('url',$this->url,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
/**
* Returns the static model of the specified AR class.
* Please note that you should have this exact method in all your CActiveRecord descendants!
* @param string $className active record class name.
* @return Item the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
}
Код: Выделить всё
<?php
class ItemController extends Controller
{
/**
* @var string the default layout for the views. Defaults to '//layouts/column2', meaning
* using two-column layout. See 'protected/views/layouts/column2.php'.
*/
public $layout='//layouts/column2';
/**
* @return array action filters
*/
public function filters()
{
return array(
'accessControl', // perform access control for CRUD operations
'postOnly + delete', // we only allow deletion via POST request
);
}
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* @return array access control rules
*/
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('index','view'),
'users'=>array('*'),
),
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('create','update'),
'users'=>array('@'),
),
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'actions'=>array('admin','delete'),
'users'=>array('admin'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
/**
* Displays a particular model.
* @param integer $id the ID of the model to be displayed
*/
public function actionView($id)
{
$this->render('view',array(
'model'=>$this->loadModel($id),
));
}
/**
* Creates a new model.
* If creation is successful, the browser will be redirected to the 'view' page.
*/
public function actionCreate()
{
$model=new Item;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Item']))
{
$model->attributes=$_POST['Item'];
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
$this->render('create',array(
'model'=>$model,
));
}
/**
* Updates a particular model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id the ID of the model to be updated
*/
public function actionUpdate($id)
{
$model=$this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Item']))
{
$model->attributes=$_POST['Item'];
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
$this->render('update',array(
'model'=>$model,
));
}
/**
* Deletes a particular model.
* If deletion is successful, the browser will be redirected to the 'admin' page.
* @param integer $id the ID of the model to be deleted
*/
public function actionDelete($id)
{
$this->loadModel($id)->delete();
// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
if(!isset($_GET['ajax']))
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
}
/**
* Lists all models.
*/
public function actionIndex()
{
$dataProvider=new CActiveDataProvider('Item');
$this->render('index',array(
'dataProvider'=>$dataProvider,
));
}
/**
* Manages all models.
*/
public function actionAdmin()
{
$model=new Item('search');
$model->unsetAttributes(); // clear any default values
if(isset($_GET['Item']))
$model->attributes=$_GET['Item'];
$this->render('admin',array(
'model'=>$model,
));
}
/**
* Returns the data model based on the primary key given in the GET variable.
* If the data model is not found, an HTTP exception will be raised.
* @param integer $id the ID of the model to be loaded
* @return Item the loaded model
* @throws CHttpException
*/
public function loadModel($id)
{
$model=Item::model()->findByPk($id);
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
return $model;
}
/**
* Performs the AJAX validation.
* @param Item $model the model to be validated
*/
protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']) && $_POST['ajax']==='item-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
}
des1roer писал(а):как настроить чтобы увидел?
Код: Выделить всё
if($model->save())
$this->redirect(array('view','id'=>$model->id));
Код: Выделить всё
$sql = " SELECT COALESCE(setval('techbase.item_id_seq', max(id)),nextval('techbase.item_id_seq')) FROM techbase.item,
(SELECT
nextval('techbase.item_id_seq')) as sel";
$connection = Yii::app()->db;
$id = $connection->createCommand($sql)->queryScalar() + 1;
код исправьте по psr-1/psr-2, чтобы исключить все сайд-эффекты, и продебажьте.des1roer писал(а):up! никто чтоли с постгрес не работал?
причем тут постгрес?des1roer писал(а):использовал это руководство
http://copist.ru/blog/2013/10/09/yii-postgresql-schema/
а при чем тут Руководство по оформлению кода
Код: Выделить всё
ini_set('display_errors', 1);
error_reporting(E_ALL);
и? следуйте psr-1/psr-2des1roer писал(а):автоформатирование netbeans
ошибка в форматировании не является ошибкой, которая будет найдена.des1roer писал(а):и проверка на ошибки включена.
я вижу, т.к. вы даже не понмиаете о чем я говорю.des1roer писал(а):я в действительности не думаю что код стайл может быть причиной ошибкиКод: Выделить всё
ini_set('display_errors', 1); error_reporting(E_ALL);
причем тут разность баз? у вас что, автоинкремент не работает?des1roer писал(а):сошлись на разности баз
https://github.com/yiisoft/yii/issues/3 ... -132148812
Код: Выделить всё
CREATE TABLE vgok_site.inc (
id SERIAL,
name TEXT NOT NULL,
CONSTRAINT inc_name_key UNIQUE(name),
CONSTRAINT inc_pkey PRIMARY KEY(id)
)
WITH (oids = false);
COMMENT ON COLUMN vgok_site.inc.id
IS 'id';
COMMENT ON COLUMN vgok_site.inc.name
IS 'имя';
Код: Выделить всё
CREATE SEQUENCE vgok_site.inc_id_seq
INCREMENT 1 MINVALUE 1
MAXVALUE 9223372036854775807 START 1
CACHE 1;
ALTER SEQUENCE vgok_site.inc_id_seq RESTART WITH 1;
Код: Выделить всё
<?php
class Inc extends CActiveRecord
{
public function tableName()
{
return 'inc';
}
public function rules()
{
return array(
array('name', 'required'),
array('id, name', 'safe', 'on' => 'search'),
);
}
public function relations()
{
return array(
);
}
public function attributeLabels()
{
return array(
'id' => 'id',
'name' => 'имя',
);
}
public function search()
{
$criteria = new CDbCriteria;
$criteria->compare('id', $this->id);
$criteria->compare('name', $this->name, true);
return new CActiveDataProvider($this, array(
'criteria' => $criteria,
));
}
public static function model($className = __CLASS__)
{
return parent::model($className);
}
}
Код: Выделить всё
public function actionCreate()
{
$model = new Inc;
if (isset($_POST['Inc']))
{
$transaction = Yii::app()->db->beginTransaction();
try
{
$model->attributes = $_POST['Inc'];
if ($model->save())
{
$transaction->commit();
Yii::app()->user->setFlash($messageType, $message);
$this->redirect(array('view', 'id' => $model->id));
}
}
catch (Exception $e)
{
$transaction->rollBack();
Yii::app()->user->setFlash('error', "{$e->getMessage()}");
}
}
$this->render('create', array(
'model' => $model,
));
}
тогда это не причем.des1roer писал(а):работает