Saving hasOne not working. Need an example


I am trying to save a hasOne relation, but i cannot seem to get it working, the cookbook isn’t helpful either with different explanations on what should be done.

i have a Users table:

id char(36) 
username varchar255 

and a Zones table:

id char(36)
user_id char(36)

Zones has:

$this->belongsTo('Users', [
    'foreignKey' => 'user_id',
    'joinType' => 'INNER'

Users has:

   $this->hasOne('Zones', [
            'foreignKey' => 'user_id'

On editing a user I would like to get a dropdown with Zones in the Zones table. If selecting a Zone and saving the user_id should be filled in at the Zones table.

Is a zone has a user_id it can no longer be used for other users.

I baked a edit controller and view. What should i do to get this working, if at all possible?


Generally bake will create HasMany associations instead of HasOne, as the two relation types use the same schema, and HasMany is more prevalent.

Your form should likely have an input in your edit view that looks like

echo $this->Form->input('')

While your edit action should contain code that looks like:

$user = $this->Users->get($id, ['contain' => ['Zones']]);
$user = $this->Users->patchEntity($user, $this->request->data(), ['associated' => ['Zones']]);
$this->Users->save($user, ['associated' => ['Zones']]);

The documentation has a brief section on creating forms for the various association types.


could u solve ur problem?
Im currently facing the same problem, except that I have a hasMany association. The link, markstory posted, is causing an error “Cannot marshal data”.

I dont want to open a new thread here, because this seems to be quite a common problem. So would be great, if u reply and let me know how u solved ur problem.