【问题标题】:Saving HasMany Associations Data in CakePHP 3.x在 CakePHP 3.x 中保存 HasMany 关联数据
【发布时间】:2016-04-10 09:45:08
【问题描述】:

我有两张桌子。我的主桌是Students。我的辅助表是Exams。我正在尝试使用 hasManybelongsToMany 关联来保存这两个表。但它仅将数据保存在 Student 表中,而不是保存在 Exams 中。谁能帮我解决这个问题。

学生模型:

class StudentsTable extends Table {
  public function initialize(array $config) {
    $this->addBehavior('Timestamp');
    parent::initialize($config);
    $this->table('students');
    $this->primaryKey(['id']);
    $this->hasMany('Exams', [
      'className' => 'Exams',
      'foreignKey' => 'student_id',
      'dependent'=>'true',
      'cascadeCallbacks'=>'true']);
  }
}

考试模式:

class ExamsTable extends Table {
  public function initialize(array $config) {
    parent::initialize($config);
    $this->table('exams');
    $this->primaryKey(['id']);
    $this->belongsToMany('Students',[
      'className'=>'Students',
      'foreignKey' => 'subject_id',
      'dependent'=>'true',
      'cascadeCallbacks'=>'true']);
  }
}

我的学校.ctp:

echo $this->Form->create();
echo $this->Form->input('name');
echo $this->Form->input('exams.subject', array(
  'required'=>false,
  'multiple' => 'checkbox',
  'options' => array(
    0 => 'Tamil',
    1 => 'English',
    2 => 'Maths')));
echo $this->Form->button(__('Save'));
echo $this->Form->end();

在我的控制器中:

public function school() {
  $this->loadModel('Students');
  $this->loadModel('Exams');
  $student = $this->Students->newEntity();
  if ($this->request->is('post')) {
    $this->request->data['exams']['subject'] =
      implode(',',$this->request->data['exams']['subject']);
    $student = $this->Students->patchEntity(
      $student, $this->request->data, ['associated' => ['Exams']]
    );
    if ($this->Students->save($student)) {
      $this->Flash->success(__('The user has been saved.'));
    } else {
      $this->Flash->error(__('Unable to add the user.'));
    }
  }
}

【问题讨论】:

  • 修补实体后$student->getErrors()的输出是什么。

标签: php mysql orm associations cakephp-3.0


【解决方案1】:

Patching BelongsToMany Associations

您需要确保自己能够设置考试。设置accessibleFields以允许您修补关联数据

$student = $this->Students->patchEntity(
  $student, $this->request->data, [
      'associated' => ['Exams'],
      'accessibleFields' => ['exams' => true]
  ]
);

您也可以使用实体中的 $_accessible 属性来执行此操作。

【讨论】:

    【解决方案2】:

    我从来没有做过 hasMany to belongsToMany 因为我不认为它是这样工作的(我的意思是没有伤害我的话。)但我会试着解释一下。你的关系应该是属于ToMany,因为考试会有很多学生,学生会有很多考试。所以基本上它们都是一样的。你需要的是另一个表来连接它们,它将被称为students_examsexams_students(我认为它的exams_students,因为E 在S 之前)因为在蛋糕中,如果你正确命名所有内容,大部分都会自动发生。

    假设您知道patchEntity 的工作原理,正确创建$this->request->data 将自动修补它并在您保存时将其保存在正确的表中。如果您还有其他问题,请随时提出更多问题。 :)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-18
      • 1970-01-01
      • 2015-11-07
      相关资源
      最近更新 更多