CakePHP 3: Save deep associated data

enter image description here

This db diagram is part of web application.

On JobsController i have apply($id) method where user (candidate) must add:

  • Applications.cover_letter
  • Applications.attachment (CV)

and many answers (yes / no) at questions related to job:

  • Answers.answer

When user submit form app create new records at applications and answers table, but answers table must contain new created applications_id.

First question:

How to create forms for deep associated tables (answers) at Jobs/apply.ctp ?

<?= $this->Form-input('applications.0.cover_letter); ?>

but for many answers?

<?= $this->Form-input('questions.0.answers.answer'); ?>
<?= $this->Form-input('questions.0.answers.question_id); ?>
<?= $this->Form-input('questions.1.answers.answer'); ?>
<?= $this->Form-input('questions.1.answers.question_id); ?>

?

Form:

  <?= $this->Form->create($job); ?>               
    // Job hasMany Applications (Applicants)
    <?= $this->Form->input('applications.0.cover_letter',['type' => 'textarea']); ?>
    <?= $this->Form->hidden('applications.0.job_id',['value' => $job->id]); ?>
        
    <?php foreach ($job->questions as $key => $questions): ?>
       // Job hasMany Question
        <?= $questions->question; ?>

        // Application hasMany Answers
        <?= $this->Form->hidden(sprintf('applications.0.answers.%s.question_id', $key),[
              'value' => $questions->id
              ]); ?>
        <?= $this->Form->radio(sprintf('applications.0.answers.%s.answer', $key),[
              ['value' => 0, 'text' => __('No')],
              ['value' => 1, 'text' => __('Yes')],
              ]); ?><
     <?php endforeach; ?>  

    <?= $this->Form->submit('Apply'); ?>
<?= $this->Form->end(); ?>

JobsController

public function apply($id = null)
{
    $job = $this->Jobs->get($id, [
        'contain' => ['Applications','Questions','Applications.Answers']
    ]);
    if ($this->request->is(['patch', 'post', 'put'])) {
        $job = $this->Jobs->patchEntity($job, $this->request->data,['associated' => ['Applications','Applications.Answers']]);
        if ($this->Jobs->save($job)) {
            $this->Flash->success(__('The Application has been saved.'));
            return $this->redirect(['action' => 'index']);
        } else {
            $this->Flash->error(__('The Application could not be saved. Please, try again.'));
        }
    }
    $this->set(compact('job'));
    $this->set('_serialize', ['job']);
}