开发者

YII + beforeSave() + getting max value from a table row

开发者 https://www.devze.com 2023-03-02 20:40 出处:网络
i\'m struggling to get my beforesave in Yii Framework working this way: when the user sends the form, beforesave() should fetch the highest number in a column called \'order\' and insert a value of

i'm struggling to get my beforesave in Yii Framework working this way:

when the user sends the form, beforesave() should fetch the highest number in a column called 'order' and insert a value of order+1 into current 'order' field.

After a few hours spent here reading posts i managed to compile this thing:

 public function beforeSave()

 {

   if (parent::beforeSave())
   {

        if($this->isNewRecord)
        {

             $criteria->select='max(order) as myMaxOrder';

             $get_it= new CActiveDataProvider(get_class($this), 
             array('criteria'=>$criteria,));

             $got_it=$get_it->getData();

             $whatweneed=$got_it[0]['myMaxOrder'];

             $this->order=(int)$whatweneed+1;

        }

        return tru开发者_运维技巧e;
    }
    else
    return false;
 }

The code gets the MAX from 'order' but i really did't know how to deal properly with the YII's getData() method, so i var_dumped it and saw that what i was looking was there but i still don't know how to access this value apart from doing

 $whatweneed=$got_it[0]['myMaxOrder'];

Could you tell me how to do it right?


If you set up your database so that the Order id is the Primary Key (it should already be anyway), just set it to "Auto Increment". If Auto Increment is set on your Primary Key (id), then when you save() a Model in Yii without an id it will automatically save it with an id one higher than the max. You won't need to do anything in beforeSave() at all! It is free functionality.

But perhaps I am totally misunderstanding your question. Maybe this is not an auto-incrementing primary key column for some reason. In that case, something like this should work (assuming your model is Order and you column is also, for some reason, called "order"):

$maxOrderNumber = Yii::app()->db->createCommand()
  ->select('max(order) as max')
  ->from('order')
  ->queryScalar();
$this->order = $maxOrderNumber + 1;

Good luck!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号