0
votes

I have a table "emailsettings" which has a "belongsTo" relationship with table "users".

emailsettings has the following columns:

  • user_id (INT)
  • subscribed (NULL, 0 or 1)
  • newsletter (NULL, 0 or 1)
  • notifications (NULL, 0 or 1)

My problem is, I'm not able to update the entries, CakePHP always tries to INSERT a new row, even if I do $this->Emailsetting->user_id = 1.

Is it possible that an associated table needs an "id" primaryKey or can I force CakePHP to update an entry if I have the "user_id" (adding an id primaryKey doesn't make sense to me, so I figure there has to be an issue with my setup).


Emailsetting.php

<?php
class Emailsetting extends AppModel {
    public $name = 'Emailsetting';
    public $belongsTo = array('User' => array('className' => 'User', 'foreignKey' => 'user_id'));
    public $useTable = 'email_settings';
} 

User.php

<?php
class User extends AppModel {
    public $name = 'User';
    public $hasOne = array('Profile', 'Emailsetting');
}
2

2 Answers

1
votes

Setting var $primaryKey = 'user_id'; inside my "Emailsetting.php"-Model, seems to do the trick, though is this the right approach?

1
votes

Though var $primaryKey = 'user_id'; does the trick and solve the problem, but according to CakePHP convention, every table should have an id field and I think its mostly acceptable.

Because, if you need to make a relation with one/more table(s) with emailsettings table, in that scenario, id will play a key role both for relation and query operations. Otherwise, you need to manually map all those relations ans queries to the primary key user_id.

Your approach is right, if working with tables, have NO access to change them by you.

Moreover, a unique id field, often usable for different actions like delete, edit etc. May be sometimes also need for different JS/AJAX operations and so on.

So, lastly I would recommend you to use id field. Becasuse, CakePHP is big fans of convention over configuration.