php - 在 CakePHP 3.x 中保存 HasMany 关联数据

标签 php mysql orm associations cakephp-3.0

我有两张 table 。我的主表是Students。我的辅助表是考试。我正在尝试使用 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();

在我的 Controller 中:

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

最佳答案

Patching BelongsToMany Associations

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

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

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

关于php - 在 CakePHP 3.x 中保存 HasMany 关联数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34630804/

相关文章:

php - CodeIgniter Datalink 与 MySQL 和 MSSQL

android - 自动删除 ORMLite 中的嵌套对象

php - 如何根据date_time从数据库中按降序获取数据?

windows-7 - Windows PHP-FPM 可以同时处理多个请求吗?

javascript - 如何从动态创建的php文件中读取echo并刷新div中的echo

php - 插入空闲id MYSQL

php - 在非线程环境中使用线程安全扩展 (APC) 有什么危害吗? (PHP)

mysql - 如何在MySQL中减去上一年,但添加月份?

java - 使用 CriteriaBuilder 的 JPA 计数(*)。如何使用 CriteriaBuilder 检索 count(*) 列

java - hql查询获取数据和金额总和