CakePHP 4: Save Has Many

Hello,

I’ve 3 tables:

users
-id
-name
-email

emails
-id
-user_id
-subject
-content

user_emails
-id
-user_id
-email_id

User model:
$this->hasMany(‘UserEmails’, [
‘foreignKey’ => ‘user_id’,
]);

Email model:
$this->hasMany(‘UserEmails’, [
‘foreignKey’ => ‘email_id’,
]);

$this->belongsTo(‘Users’, [
‘foreignKey’ => ‘user_id’,
‘joinType’ => ‘INNER’,
]);

email controller:
public function add()
{
$this->loadModel(‘Users’);

	$users = $this->Emails->Users->find('list', [
		'keyField' => 'email',
		'valueField' => function ($row) {
			return $row['name'] . ' - ' . $row['email'];
		}
	]);

    $email = $this->Emails->newEmptyEntity();
    if ($this->request->is('post')) {
		
	$mailto = $this->request->getData('mailto');
	debug($mailto);
	exit;
		
        $email = $this->Emails->patchEntity($email, $this->request->getData());
        if ($this->Emails->save($email)) {
            $this->Flash->success(__('The email has been saved.'));
            return $this->redirect(['action' => 'index']);
        }
        $this->Flash->error(__('The email could not be saved. Please, try again.'));
    }
    $this->set(compact('email','users'));
}

The emails table is used to store sent email. In the user_emails interface, i’ve create the ‘mailto’ input field where it render options based on email from users table. when i debug, the mailto data request, it shows as follow:

APP/Controller\EmailsController.php (line 62)

[
(int) 0 => ‘a@gmail.com’,
(int) 1 => ‘b@gmail.com’,
(int) 2 => ‘c@gmail.com’,
]

How can I save the multiple selected email into the user_emails table?

Thank you

you can save many (not plural)

$entities = $articles->newEntities($this->request->getData());

See Converting HasMany Data