Simple CakePHP ActiveRecord save problem: Why does the field save `NULL` instead of the value I assign it?

1.3k Views Asked by At

First, I've been using CakePHP for a long time, and I'm very comfortable with the API. I'm pretty sure this is going to be a face-palm error, but I'll need some fresh eyes on this because I've been stuck for over an hour.

I have three models, User, Job, and Company.

  1. Company hasMany User
  2. Company hasMany Job

Sometimes, when a user is updating a job record, the user needs to change the job's company_id field. When this happens, I also have a requirement to change the user's own company_id field. So, in effect, the User and the Job will both be re-assigned to a different company.

In the CRUD update method of the JobsController, I have added this logic:

$this->Job->User->read(NULL, $this->Session->read('User.id'));
$this->Job->User->set('company_id', $this->data['Job']['company_id']);
$this->Job->User->save();

I have verified using typical debugging techniques, like var_dump() that $this->Session->read('User.id') contains a proper value, and $this->data['Job']['company_id'] contains the correct value that was submitted from the form helper.

The correct User record is updated, because the modified timestamp in the table indicates that it is so, but the company_id field is set to NULL instead of the correct company_id from the data array.

Interestingly, after the above snippet I save the Job record, and it does get updated with the correct company_id (using the same $this->data array).

It's just $this->Job->User->save() that seems to pass a NULL value to the table.

<facepalm type="lame">

Turns out a new junior dev monkeyed with the code at a further point in the application flow. This dev was trying to complete the same ticket, and incorrectly executed a save method loaded with NULL data (after the job data save, which is why I didn't notice, since I was working before the job save...).

At any rate, walking down the SQL dump made me find the error, so credit should be given to @dhofstet for pointing me down the right debug path. Thank goodness for version control.

</facepalm>

2

There are 2 best solutions below

0
On

Why so complicated?

a simple

$this->Job->User->save($this->data);

will to the trick

assuming you fill up the array with [User][company_id] etc

6
On

Have you checked that $this->data['Job']['company_id'] is not null? Maybe there is some problem with validation. Have you tried saveField instead set & save?