CakePHP 3: belongToMany using the ‘through’ Option & How to save?

I have a little problem, I need to create friendships system, using ‘through’ option, but I can not find in documentation how to save extra data in the joint / pivot table.

In Candidates Table (User table)

    $this->belongsToMany('Users', [
        'foreignKey' => 'requester_id',
        'targetForeignKey' => 'recipient_id',
        'joinTable' => 'connections',
        'through' => 'Connections'

In connections table need to save additional data, (status, banned_by, created, modified,…)

How to do it? if my association set right?

You need to create/bake the ConnectionsTable and entity. Then when you create/patch the candidates, you can set the _joinData key in the array/entity like the cookbook says.

1 Like

I will suggest you go through this particular section of the cakephp book

1 Like

I had a table called Users and Address Table and I created models and controller with baking it.

and I was able to save the data like this

requested json data: {“username”:“abcd”, … “addresses”[{}.{}.{}]

the code inside edit fuc
we just need to update code inside edit.

public function edit($id = null) {
$this->Crud->on(‘beforeFind’, function(\Cake\Event\Event $event) {
$event->subject()->query->contain([ ‘Addresses’]);

    return $this->Crud->execute();

if you still have some doubt.

Please let me know.


Thanks to all for support