Cakephp 3 - Save associated belongsToMany (joinTable)


#1

i have a question about saving a new entity with an association which is a belongsToMany relation. Just a quick introduction. I have something like a settings table and a setting_values table. The user is connected to the settings by a joinTable called users_settings. So in summary:

settings:
id | name

setting_values:
id | setting_id | name | value |

users_settings:
id | user_id | setting_id | setting_value_id

Now before the user is added I want to patch the entity of the user with all settings and the first setting_value for each setting. So that users_settings has now all settings connected to the user with the first value. But I can’t get the patch or the newEntity to be work. All models are baked so this should be fine. Here’s my code

$settings = $this->Settings->find('all', [
            'contain' => [
                'SettingValues'
            ]
        ]);

$settingsData = [];

foreach ($settings as $setting) {
    $settingsData[] = [
        'setting_id' => $setting->id,
        'setting_value_id' => $setting->setting_values[0]->id,
    ];
}

$data = [
    'users_settings' => $settingsData
];

$user = $this->Users->patchEntity($user, $data, [
    'associated' => [
        'Settings.UsersSettings'
    ]
]);

This is the result. As you can see nothing is corretly marshaled:

users_settings => [
	(int) 0 => [
		setting_id => (int) 1,
		setting_value_id => (int) 1
	],
	(int) 1 => [
		setting_id => (int) 2,
		setting_value_id => (int) 5
	]
]

Can someone give me an advice on this. Thanks


#2
'associated' => [
    'UserSettings'
]

shoud be 'UsersSettings'


#3

Actually that was my fault. In the code it’s Settings.UsersSettings. Otherwise I got the following error:

Error: Cannot marshal data for UsersSettings association. It is not associated with Users


#4

ah you didnt post your Users table, but i can see there is ‘user_id’ inside ‘users_settings’ so you can just add it to it.


#5

This was the solution:

$data = [
    'settings' => [
        [
            'id' => 1,
            '_joinData' => [
                'setting_value_id' => 1
            ]
        ],
        [
            'id' => 2,
            '_joinData' => [
                'setting_value_id' => 5
            ]
        ]
    ]
];

$user = $this->Users->patchEntity($user, $data, [
    'associated' => [
        'Settings._joinData'
    ]
]);