beforesave() + getting max value from a table

Hi there,

i’m struggling to get my beforesave 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:




   protected 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 true;

            }

            else

            return false;

        }



It gets the MAX from ‘order’ but i really did’t know how to deal properly with the 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?

Uhm, why so complicated? Something like this should do it:




function beforeSave()

{

    if (parent::beforeSave() && $this->isNewRecord) {

        $this->order=$this->dbConnection->createCommand('SELECT MAX(order)+1 FROM ..tablename here...')->queryScalar();

        return true;

}

Hi Mike!

I saw your posts helping people all around including me, thank you for helping me with this thing!

Cheers :)