Wrong user_id after saving why?

Hello, i wrote a function to add a friend to a user but if i save the $data it will use a user_id that differs from what i provided.

debug($data) shows:

APP/Controller/UsersController.php (line 243 )
[‘friends’ => [(int) 0 => [‘friendslist_id’ => (int) 7,‘user_id’ => (int) 1,‘approved’ => (int) 33333,],],

but the database entry shows: user_id’ => (int) 7

Function is:

$user = $this->Users->get($id, [
‘contain’ => [ ‘Friendslists.Friends’],
]);

$data = [
‘friends’ => [
[
‘friendslist_id’ =>$user->friendslist->id,
‘user_id’ => $this->request->getAttribute(‘identity’)->getIdentifier(),
‘approved’ => 33333,
],],

];

//debug($data);exit;
$user->setDirty(‘friends’, true);
$user = $this->Users->patchEntity($user, $data);
$this->Users->save($user);

Maybe you have a error in your asociation?

What does debug($user->friends) give you after the patchEntity call?

APP/Controller/UsersController.php (line 243)
[
(int) 0 => object(App\Model\Entity\Friend) id:0 {
‘friendslist_id’ => (int) 4
‘user_id’ => (int) 1
‘approved’ => (int) 33333
‘[new]’ => true
‘[accessible]’ => [
‘user_id’ => true,
‘friendslist_id’ => true,
‘approved’ => true,
‘created’ => true,
‘modified’ => true,
‘user’ => true,
‘friendslist’ => true,
]
‘[dirty]’ => [
‘friendslist_id’ => true,
‘user_id’ => true,
‘approved’ => true,
]
‘[original]’ => [ ]
‘[virtual]’ => [ ]
‘[hasErrors]’ => false
‘[errors]’ => [ ]
‘[invalid]’ => [ ]
‘[repository]’ => ‘Friends’
},
]

It shows the correct user_id but the database entry contains a different one…

he is using the user_id of:

$user = $this->Users->get($id, [
‘contain’ => [ ‘Friendslists.Friends’],
]);

instead of:

$data = [
‘friends’ => [
[
‘friendslist_id’ =>$user->friendslist->id,
‘user_id’ => $this->request->getAttribute(‘identity’)->getIdentifier(),

and:

$this->Users->save($user)

overwrites the user_id with the one given at the beginning…

i changed to ‘contain’ => [ ‘Friendslists’] now to load less data but it has no effect on the overwriting of the user_id

FriendsTable has both:

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