Tuesday, February 22, 2022

[FIXED] Cakephp 3.0 Multiple tables

Issue

I'm sure I am just being an idiot, but can anyone help?, the following controller is only saving to the users table, not the child "Userapikey" table (All other data is auto built by Cakephp and MySQL):

$data = $this->request->data;
// Create the default access mask
$data[ 'userapikey' ] = [
    [ 'accessmask' => 22966271 ]
];

// Create a new entity in the DB and populate
$User = $this->Users->newEntity( $data, [ 'associated' => [ 'Userapikeys' ]  );

// Commit to the database
if( $this->Users->save( $User ) ) {
// Blah Blah send message etc.
}

UserTable.php has got the

$this->hasMany('Userapikeys', [ 'foreignKey' => 'user_id' ]);

Userapikeys.php has the

$this->belongsTo('Users', [ 'foreignKey' => 'user_id' ]);

If you need any more information I would be happy to provide


Solution

Eventually found that in the User.php entity please make sure the accessible included your "child" table eg.

protected $_accessible = [
    'username' => true,
    'password' => true,
    'user_api_keys' => true
];

and make sure it is the underscored version and plural



Answered By - B1scuit

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.