postgres не работает $model->id в actionCreate

Общие вопросы по использованию фреймворка. Если не знаете как что-то сделать и это про Yii, вам сюда.
Аватара пользователя
des1roer
Сообщения: 391
Зарегистрирован: 2015.02.06, 17:03
Контактная информация:

postgres не работает $model->id в actionCreate

Сообщение des1roer »

не могу использовать $model->id в actionCreate. настройки gii по дефолту. подскажите это баг или я просто не умею готовить?
Аватара пользователя
samdark
Администратор
Сообщения: 9489
Зарегистрирован: 2009.04.02, 13:46
Откуда: Воронеж
Контактная информация:

Re: postgres не работает $model->id в actionCreate

Сообщение samdark »

Подробности давайте.
zelenin
Сообщения: 10596
Зарегистрирован: 2013.04.20, 11:30

Re: postgres не работает $model->id в actionCreate

Сообщение zelenin »

просто не умеете. связи между model->id и gii не могу углядеть.
Аватара пользователя
des1roer
Сообщения: 391
Зарегистрирован: 2015.02.06, 17:03
Контактная информация:

Re: postgres не работает $model->id в actionCreate

Сообщение des1roer »

настраиваю постгрес так http://des1roer.blogspot.ru/2015/04/yii-postgres.html
таблица предположим такая

Код: Выделить всё

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://)'; 
в gii модель

Код: Выделить всё

<?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
Сообщения: 391
Зарегистрирован: 2015.02.06, 17:03
Контактная информация:

Re: postgres не работает $model->id в actionCreate

Сообщение des1roer »

как настроить чтобы увидел?
zelenin
Сообщения: 10596
Зарегистрирован: 2013.04.20, 11:30

Re: postgres не работает $model->id в actionCreate

Сообщение zelenin »

des1roer писал(а):как настроить чтобы увидел?

Код: Выделить всё

if($model->save())
                $this->redirect(array('view','id'=>$model->id)); 
чтобы здесь вы "увидели" $model->id, должен выполниться $model->save() (вернуть true)
Аватара пользователя
des1roer
Сообщения: 391
Зарегистрирован: 2015.02.06, 17:03
Контактная информация:

Re: postgres не работает $model->id в actionCreate

Сообщение des1roer »

в плане? сохранение то происходит.
Аватара пользователя
des1roer
Сообщения: 391
Зарегистрирован: 2015.02.06, 17:03
Контактная информация:

Re: postgres не работает $model->id в actionCreate

Сообщение des1roer »

Я уж вообще парадоксальщину(костыли?) привык писать типа

Код: Выделить всё

               $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; 
Аватара пользователя
des1roer
Сообщения: 391
Зарегистрирован: 2015.02.06, 17:03
Контактная информация:

Re: postgres не работает $model->id в actionCreate

Сообщение des1roer »

up! никто чтоли с постгрес не работал?
zelenin
Сообщения: 10596
Зарегистрирован: 2013.04.20, 11:30

Re: postgres не работает $model->id в actionCreate

Сообщение zelenin »

des1roer писал(а):up! никто чтоли с постгрес не работал?
код исправьте по psr-1/psr-2, чтобы исключить все сайд-эффекты, и продебажьте.
Аватара пользователя
des1roer
Сообщения: 391
Зарегистрирован: 2015.02.06, 17:03
Контактная информация:

Re: postgres не работает $model->id в actionCreate

Сообщение des1roer »

использовал это руководство
http://copist.ru/blog/2013/10/09/yii-postgresql-schema/
а при чем тут Руководство по оформлению кода
zelenin
Сообщения: 10596
Зарегистрирован: 2013.04.20, 11:30

Re: postgres не работает $model->id в actionCreate

Сообщение zelenin »

des1roer писал(а):использовал это руководство
http://copist.ru/blog/2013/10/09/yii-postgresql-schema/
а при чем тут Руководство по оформлению кода
причем тут постгрес?
следуйте принятым в сообществе кодстайлам. у вас кодстайл 2000 года без закрывающих скобочек. не хочется обсуждать то, где могут быть такие нелепые ошибки.
Аватара пользователя
des1roer
Сообщения: 391
Зарегистрирован: 2015.02.06, 17:03
Контактная информация:

Re: postgres не работает $model->id в actionCreate

Сообщение des1roer »

автоформатирование netbeans и проверка на ошибки включена.

Код: Выделить всё

ini_set('display_errors', 1);
error_reporting(E_ALL); 
я в действительности не думаю что код стайл может быть причиной ошибки
zelenin
Сообщения: 10596
Зарегистрирован: 2013.04.20, 11:30

Re: postgres не работает $model->id в actionCreate

Сообщение zelenin »

des1roer писал(а):автоформатирование netbeans
и? следуйте psr-1/psr-2
des1roer писал(а):и проверка на ошибки включена.
ошибка в форматировании не является ошибкой, которая будет найдена.
des1roer писал(а):

Код: Выделить всё

ini_set('display_errors', 1);
error_reporting(E_ALL);
я в действительности не думаю что код стайл может быть причиной ошибки
я вижу, т.к. вы даже не понмиаете о чем я говорю.
zelenin
Сообщения: 10596
Зарегистрирован: 2013.04.20, 11:30

Re: postgres не работает $model->id в actionCreate

Сообщение zelenin »

des1roer писал(а):сошлись на разности баз
https://github.com/yiisoft/yii/issues/3 ... -132148812
причем тут разность баз? у вас что, автоинкремент не работает?
Аватара пользователя
des1roer
Сообщения: 391
Зарегистрирован: 2015.02.06, 17:03
Контактная информация:

Re: postgres не работает $model->id в actionCreate

Сообщение des1roer »

ddl

Код: Выделить всё

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
Сообщения: 391
Зарегистрирован: 2015.02.06, 17:03
Контактная информация:

Re: postgres не работает $model->id в actionCreate

Сообщение des1roer »

где тут можно ошибиться? однако не срабатывает. видать yii действительно SEQUENCE не видит
zelenin
Сообщения: 10596
Зарегистрирован: 2013.04.20, 11:30

Re: postgres не работает $model->id в actionCreate

Сообщение zelenin »

des1roer писал(а):работает
тогда это не причем.
Ставьте брейкпойнты: сохраняется ли запись, в каком виде сохраняется запись, в каком виде она доступна после сохранения.
Ответить