将数据保存到另一个模型cakePHP 3.5 [英] Save data to another model cakePHP 3.5

查看:80
本文介绍了将数据保存到另一个模型cakePHP 3.5的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我仍然是cakephp的初学者。我有桌问和题测验。我已经在问题控制器中创建了名为existingQuestion的表单,并希望将其保存在表questionQuizzes中。但是,该表单无法保存。我已经遵循了这个示例,但仍然无法保存。

I'm still beginner in cakephp. I have table question and questionQuizzes. I have created the form named existingQuestion in question controller and want to save it in table questionQuizzes. However, the form cannot be saved. I have followed this example but it still cannot be saved.

这是QuestionController

This is 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:
这是我的现存的question.ctp

Edited 3: This is my 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,问题和标记。然后,我有一个表QuestionQuizzes,其中包含测验ID和问题ID。

Edited 4: I have table quizzes which contains id and quiz id. And I have table questions contains id, question id, questions and marks. Then, I have table questionQuizzes which contains quiz id and question id.

这是quizzesTable.php模型:

Here is quizzesTable.php model:

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

Here is 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: existques function:

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']);
    }
}


推荐答案

您的数据格式错误。您在哪里找到的?看起来应该像这样:

Your data is in the wrong format. Where did you find this? It should look like this:

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

请注意,问题是现在小写和复数,并且id替换为_ids。有关更多详细信息,请参见此处

Note that questions is now lower case and plural, and id is replaced with _ids. See here for more details.

您还将希望将其移至Quizzes控制器(正如我建议的),然后对测验实体进行 patchEntity (通过Quizzes模型),因为现在您拥有的数据毫无意义:它怎么知道应该将这些问题添加到什么测验中?

You will also want to move this to the Quizzes controller (as I suggested last time) and do patchEntity on a quiz entity (through the Quizzes model), because right now the data you have is meaningless: how does it know what quiz it's supposed to be adding these questions to?

这篇关于将数据保存到另一个模型cakePHP 3.5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆