将数据保存到另一个模型cakePHP 3.5

时间:2017-12-27 07:43:01

标签: php database cakephp cakephp-3.x

我还是在cakephp的初学者。我有表问题和问题测验。我在问题控制器中创建了名为existingQuestion的表单,并希望将其保存在表questionQuizzes中。但是,表单无法保存。我已按照此example但仍无法保存。

这是QuestionController

public function existingQuestion()
{  

    //echo "here<br><br>";
    //$QuestionQuizzesTable = 
    $this->loadModel('QuestionQuizzes');
    $questions = $this->paginate($this->Questions);
    $questionQuiz = $this->QuestionQuizzes->newEntity();

    //print_r($this->request->getData());
    //die();

    if($this->request->is('post'))
    {

        $questionQuiz = $this->QuestionQuizzes->patchEntity($questionQuiz, $this->request->getData());
        print_r($this->request->getData());
        die();

        if ($this->QuestionQuizzes->save($questionQuiz)) {
            $this->Flash->success(__('The question has been saved.'));

            return $this->redirect(['action' => 'existingQuestion']);
        }
        $this->Flash->error(__('The question could not be saved. Please, try again.'));
    }

    //$this->Questions->saveAll($this->request->getData());
    $this->set(compact('questions'));
    $this->set('_serialize', ['questions']);
}

有人能帮助我吗??!

编辑3: 这是我的existing_questions.ctp

<?php

 /**
 * @var \App\View\AppView $this
 * @var \App\Model\Entity\Question[]|\Cake\Collection\CollectionInterface 
  $questions
  */
  use Cake\ORM\TableRegistry;
  ?>
  <nav class="large-3 medium-4 columns" id="actions-sidebar">
   <ul class="side-nav">
    <li class="heading"><?= __('Actions') ?></li>
    <li><?= $this->Html->link(__('Courses'), ['controller' => 'Courses',  
    'action' => 'index']) ?></li>
    </ul>
    </nav>
   </nav>
    <div class="questions form large-9 medium-8 columns content">
    <fieldset>
    <legend><?= __('Add Question') ?></legend>
    <?php echo $this->Form->create($questionQuiz) ?>  
    <table cellpadding="0" cellspacing="0">
    <thead>
        <tr>
            <th scope="col"><?= $this->Paginator->sort('checked') ?></th>
            <th scope="col"><?= $this->Paginator->sort('id') ?></th>
            <th scope="col"><?= $this->Paginator->sort('question') ?></th>
            <th scope="col"><?= $this->Paginator->sort('marks') ?></th>
        </tr>
    </thead>
    <tbody>
        <?php foreach ($questions as $question): ?>
        <tr>
            <td><?= $this->Form->checkbox('questions[].', ['value' => 
            $question['id'], 'name' => 'question[id][]', 'checked'=>false, 
                'hiddenField' => false])?></td>
               <td><?= $this->Number->format($question->id) ?></td>
                <td><?= h($question->question) ?></td>
                <td><?= $this->Number->format($question->marks) ?></td>
        </tr>
        <?php endforeach; ?>                 
    </tbody>
    </table>
    <input type="submit" value="Save">        
    </form>
    <div class="paginator">
    <ul class="pagination">
        <?= $this->Paginator->first('<< ' . __('first')) ?>
        <?= $this->Paginator->prev('< ' . __('previous')) ?>
        <?= $this->Paginator->numbers() ?>
        <?= $this->Paginator->next(__('next') . ' >') ?>
        <?= $this->Paginator->last(__('last') . ' >>') ?>
    </ul>
    <p><?= $this->Paginator->counter(['format' => __('Page {{page}} of {{pages}}, showing {{current}} record(s) out of {{count}} total')]) ?></p>
     <?php //$this->Form->button(__('Submit'), ['action' => 'existingQuestion'])
         $this->Form->submit('Save'); 
        // $this->Form->end() ?>
</div>
</fieldset>
</div>

编辑4: 我有桌面测验,其中包含id和测验ID。我有表格问题包含id,问题ID,问题和标记。然后,我有table questionQuizzes,其中包含测验ID和问题ID。

这是quizzesTable.php模型:

class QuizzesTable extends Table
{

/**
 * Initialize method
 *
 * @param array $config The configuration for the Table.
 * @return void
 */
public function initialize(array $config)
{
    parent::initialize($config);

    $this->setTable('quizzes');
    $this->setDisplayField('title');
    $this->setPrimaryKey('id');

    $this->belongsTo('Courses', [
        'foreignKey' => 'course_id',
        'joinType' => 'INNER'
    ]);
    $this->hasMany('Attempts', [
        'foreignKey' => 'quiz_id'
    ]);
    $this->hasMany('Gradebooks', [
        'foreignKey' => 'quiz_id'
    ]);
}

/**
 * Default validation rules.
 *
 * @param \Cake\Validation\Validator $validator Validator instance.
 * @return \Cake\Validation\Validator
 */
public function validationDefault(Validator $validator)
{
    $validator
        ->integer('id')
        ->allowEmpty('id', 'create');

    $validator
        ->scalar('title')
        ->requirePresence('title', 'create')
        ->notEmpty('title');

    return $validator;
}

/**
 * Returns a rules checker object that will be used for validating
 * application integrity.
 *
 * @param \Cake\ORM\RulesChecker $rules The rules object to be modified.
 * @return \Cake\ORM\RulesChecker
 */
public function buildRules(RulesChecker $rules)
{
    $rules->add($rules->existsIn(['course_id'], 'Courses'));

    return $rules;
}
}

这是questionsTable.php

class QuestionsTable extends Table
{

/**
 * Initialize method
 *
 * @param array $config The configuration for the Table.
 * @return void
 */
public function initialize(array $config)
{
    parent::initialize($config);

    $this->setTable('questions');
    $this->setDisplayField('id');
    $this->setPrimaryKey('id');

    $this->hasMany('QuestionQuizzes', [
        'foreignKey' => 'question_id'
    ]);
}

/**
 * Default validation rules.
 *
 * @param \Cake\Validation\Validator $validator Validator instance.
 * @return \Cake\Validation\Validator
 */
public function validationDefault(Validator $validator)
{
    $validator
        ->integer('id')
        ->allowEmpty('id', 'create');

    $validator
        ->scalar('question')
        ->requirePresence('question', 'create')
        ->notEmpty('question');

    $validator
        ->numeric('marks')
        ->requirePresence('marks', 'create')
        ->notEmpty('marks');

    return $validator;
}
}

EDITED: 存在功能:

public function existQues()
{
    $questions = TableRegistry::get('questions');
    $query = $questions->find();

    foreach ($query as $row) 
    {
        $quizzes = $this->paginate($this->Quizzes);

        $this->set(compact('quizzes'));
        $this->set('_serialize', ['quizzes']);
    }
}

1 个答案:

答案 0 :(得分:0)

您的数据格式错误。你在哪里找到这个?它应该是这样的:

[
    'questions' => [
        '_ids' => [
            0 => 60,
            1 => 61,
        ]
    ]
]

请注意,问题现在是小写和复数,而id用_ids替换。有关详细信息,请参阅here

您还需要将其移至测验控制器(我建议last time)并在测验实体上执行patchEntity(通过测验模型),因为您现在拥有的数据是毫无意义:它如何知道应该将这些问题添加到哪个小测验中?