Newly Inserted Record - Can't Get ID

Hi. I started to learn Yii to use it in a hobby project. I am following a book named ‘Web Application Development with Yii 2 and PHP’

I started with creating models and controllers, but something bugs me that I could not figured out.

I have a CustomerRecord model, which consists four fields, including primary key, labeled as id.

I have another model named PhoneRecord, which has an id, customer_id and number fields.

Book claims normally, customerRecord instance should get its primary key after $model->save(). But it simply does not.

I have enclosed my model, view and controller files.

On database, everything is working as expected. Newly inserted lines get their id’s without any problem.

I have tried updating


$customerRecord->update();  



and getting primary key


$customerRecord->getPrimaryKey();



as wel as setting $customerRecord->id to null before save.

None of them worked, id just does not get updated.

Here is the var_dump outputs of the model, before and after $customerRecord->save();


customer before save


object(app\models\customer\CustomerRecord)[61]

  private '_attributes' (yii\db\BaseActiveRecord) => 

    array (size=3)

      'name' => string 'John Doe' (length=<img src='http://www.yiiframework.com/forum/public/style_emoticons/default/cool.gif' class='bbc_emoticon' alt='8)' />

      'birthDate' => string '0101-0101-84848484' (length=18)

      'notes' => string 'notlar 456' (length=10)

  private '_oldAttributes' (yii\db\BaseActiveRecord) => null

  private '_related' (yii\db\BaseActiveRecord) => 

    array (size=0)

      empty

  private '_errors' (yii\base\Model) => null

  private '_validators' (yii\base\Model) => null

  private '_scenario' (yii\base\Model) => string 'default' (length=7)

  private '_events' (yii\base\Component) => 

    array (size=0)

      empty

  private '_behaviors' (yii\base\Component) => 

    array (size=0)

      empty


customer after save


object(app\models\customer\CustomerRecord)[61]

  private '_attributes' (yii\db\BaseActiveRecord) => 

    array (size=3)

      'name' => string 'John Doe' (length=<img src='http://www.yiiframework.com/forum/public/style_emoticons/default/cool.gif' class='bbc_emoticon' alt='8)' />

      'birthDate' => string '0101-0101-84848484' (length=18)

      'notes' => string 'notlar 456' (length=10)

  private '_oldAttributes' (yii\db\BaseActiveRecord) => null

  private '_related' (yii\db\BaseActiveRecord) => 

    array (size=0)

      empty

  private '_errors' (yii\base\Model) => 

    array (size=1)

      'birthDate' => 

        array (size=1)

          0 => string 'The format of Birth Date is invalid.' (length=36)

  private '_validators' (yii\base\Model) => 

    object(ArrayObject)[62]

      

        object(yii\validators\NumberValidator)[63]

          public 'integerOnly' => boolean false

          public 'max' => null

          public 'min' => null

          public 'tooBig' => null

          public 'tooSmall' => null

          public 'integerPattern' => string '/^\s*[+-]?\d+\s*$/' (length=18)

          public 'numberPattern' => string '/^\s*[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?\s*$/' (length=48)

          public 'attributes' => 

            array (size=1)

              ...

          public 'message' => string '{attribute} must be a number.' (length=29)

          public 'on' => 

            array (size=0)

              ...

          public 'except' => 

            array (size=0)

              ...

          public 'skipOnError' => boolean true

          public 'skipOnEmpty' => boolean true

          public 'enableClientValidation' => boolean true

          public 'isEmpty' => null

          public 'when' => null

          public 'whenClient' => null

          private '_events' (yii\base\Component) => 

            array (size=0)

              ...

          private '_behaviors' (yii\base\Component) => null

      

        object(yii\validators\RequiredValidator)[64]

          public 'skipOnEmpty' => boolean false

          public 'requiredValue' => null

          public 'strict' => boolean false

          public 'message' => string '{attribute} cannot be blank.' (length=28)

          public 'attributes' => 

            array (size=1)

              ...

          public 'on' => 

            array (size=0)

              ...

          public 'except' => 

            array (size=0)

              ...

          public 'skipOnError' => boolean true

          public 'enableClientValidation' => boolean true

          public 'isEmpty' => null

          public 'when' => null

          public 'whenClient' => null

          private '_events' (yii\base\Component) => 

            array (size=0)

              ...

          private '_behaviors' (yii\base\Component) => null

      

        object(yii\validators\StringValidator)[65]

          public 'length' => null

          public 'max' => int 254

          public 'min' => null

          public 'message' => string '{attribute} must be a string.' (length=29)

          public 'tooShort' => null

          public 'tooLong' => string '{attribute} should contain at most {max, number} {max, plural, one{character} other{characters}}.' (length=97)

          public 'notEqual' => null

          public 'encoding' => string 'UTF-8' (length=5)

          public 'attributes' => 

            array (size=1)

              ...

          public 'on' => 

            array (size=0)

              ...

          public 'except' => 

            array (size=0)

              ...

          public 'skipOnError' => boolean true

          public 'skipOnEmpty' => boolean true

          public 'enableClientValidation' => boolean true

          public 'isEmpty' => null

          public 'when' => null

          public 'whenClient' => null

          private '_events' (yii\base\Component) => 

            array (size=0)

              ...

          private '_behaviors' (yii\base\Component) => null

      

        object(yii\validators\DateValidator)[66]

          public 'format' => string 'dd-mm-yyyy' (length=10)

          public 'locale' => string 'en-US' (length=5)

          public 'timeZone' => string 'UTC' (length=3)

          public 'timestampAttribute' => null

          public 'timestampAttributeFormat' => null

          public 'timestampAttributeTimeZone' => string 'UTC' (length=3)

          public 'max' => null

          public 'min' => null

          public 'tooBig' => null

          public 'tooSmall' => null

          public 'maxString' => string '' (length=0)

          public 'minString' => string '' (length=0)

          private '_dateFormats' => 

            array (size=4)

              ...

          public 'attributes' => 

            array (size=1)

              ...

          public 'message' => string 'The format of {attribute} is invalid.' (length=37)

          public 'on' => 

            array (size=0)

              ...

          public 'except' => 

            array (size=0)

              ...

          public 'skipOnError' => boolean true

          public 'skipOnEmpty' => boolean true

          public 'enableClientValidation' => boolean true

          public 'isEmpty' => null

          public 'when' => null

          public 'whenClient' => null

          private '_events' (yii\base\Component) => 

            array (size=0)

              ...

          private '_behaviors' (yii\base\Component) => null

      

        object(yii\validators\SafeValidator)[67]

          public 'attributes' => 

            array (size=1)

              ...

          public 'message' => null

          public 'on' => 

            array (size=0)

              ...

          public 'except' => 

            array (size=0)

              ...

          public 'skipOnError' => boolean true

          public 'skipOnEmpty' => boolean true

          public 'enableClientValidation' => boolean true

          public 'isEmpty' => null

          public 'when' => null

          public 'whenClient' => null

          private '_events' (yii\base\Component) => 

            array (size=0)

              ...

          private '_behaviors' (yii\base\Component) => null

  private '_scenario' (yii\base\Model) => string 'default' (length=7)

  private '_events' (yii\base\Component) => 

    array (size=0)

      empty

  private '_behaviors' (yii\base\Component) => 

    array (size=0)

      empty

Any ideas?

[color="#006400"]/* Moved from 1.1 to 2.0 forum */[/color]

You are creating a new instance of Customer in this method, which is not the same instance of Customer that you are working with outside this method. "id" is updated for $customerRecord in this method, but not for $customer.

You could write simply like this:




    private function store (Customer $customer)

    {

        echo 'customer before save';

        var_dump($customer);

        $customer->save();

        echo 'customer after save';

        var_dump($customer);


        foreach ($customer->phones as $phone)

        {

            $phoneRecord = new PhoneRecord();

            $phoneRecord->number = $phone->number;

            $phoneRecord->customer_id = $customer->id;           

            $phoneRecord->save();

        }

        

    }



Hi. Thanks for your response.

That $customer parameter is not actually an active record class. It is just a regular class with plain attributes. It works as a transition layer between active record layer and rest of the app (at least, that is what the book says). It just conveys the data.

So the actual active record class is $customerRecord. And no matter what I do, id is not just getting updated :angry:

Hmm, that is strange. I have to look at your code again. But, sorry, I’m now get drunken and can’t operate my brain in a normal way (it’s 19:42pm on Sunday night here in the far east).

Hi,

could you plese post the SQL create for the table customer ?

ciao

B)

Ciao,

Prego, here it is ;)


CREATE TABLE IF NOT EXISTS `crmapp`.`customer` (

  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,

  `name` VARCHAR(255) NOT NULL,

  `birthDate` TEXT(255) NULL,

  `notes` TEXT(255) NULL,

  PRIMARY KEY (`id`))

ENGINE = InnoDB;

I have dropped and created table again with this code, just in case. Result is the same.

Figured it out. It turned out to be a validation problem. I have wrote a wrong date formatting code. I fixed the date formatting code and voila! :)

Hope that helps for someone else out there.