B1scuit
B1scuit

Reputation: 77

Cakephp 3.0 Multiple tables

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

Upvotes: 0

Views: 162

Answers (2)

B1scuit
B1scuit

Reputation: 77

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

Upvotes: 1

ADmad
ADmad

Reputation: 8100

Given that you have User hasMany UserApikeys your data array should be:

$data[ 'userapikeys' ][0] = [
    [ 'accessmask' => 22966271 ]
];

Upvotes: 1

Related Questions