复杂的多个关联保存在cakephp 3中

时间:2015-06-01 20:21:31

标签: cakephp cakephp-3.0

我正在通过EmployeesCourses表保存一个与课程的hasMany关系相关联的员工。这一切都运行正常,员工被添加,新的employee_id和course_id被创建到EmployeesCourses表中。

我现在正尝试将记录添加到员工的users表中,并在创建员工时将新的user_id与员工一起保存。所有其他记录仍然得到保存,但我没有得到任何时间的用户表和Employee.user_id

中没有ID

EmployeesController.php

public function add()
{
    $employee = $this->Employees->newEntity();
    if ($this->request->is('post')) {
        $employee = $this->Employees->patchEntity($employee, $this->request->data, [
            'associated' => ['Users', 'Courses']
        ]);
        if ($this->Employees->save($employee)) {
            $this->Flash->success(__('The employee has been saved.'));
            return $this->redirect(['action' => 'index']);
        } else {
            $this->Flash->error(__('The employee could not be saved. Please, try again.'));
        }
    }
    $businesses = $this->Employees->Businesses->find('list', ['limit' => 200]);
    $courses = $this->Employees->Courses->find('list', ['limit' => 200]);
    $this->set(compact('employee', 'users', 'businesses', 'courses'));
    $this->set('_serialize', ['employee']);
}

员工add.ctp

<?= $this->Form->create($employee) ?>
<fieldset>
    <legend><?= __('Add Employee') ?></legend>
    <?php
        echo $this->Form->input('user.email');
        echo $this->Form->input('user.new_password', ['value' => '', 'type' => 'password']);
        echo $this->Form->input('user.confirm_password', ['value' => '', 'type' => 'password']);
        echo $this->Form->input('business_id', ['options' => $hotels]);
        echo $this->Form->input('name');
        echo $this->Form->input('email');
        echo $this->Form->input('surname');
        echo $this->Form->input('employee_num');
        echo $this->Form->input('courses._ids', ['options' => $courses]);
    ?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>

员工模型

public function initialize(array $config)
{
    $this->table('employees');
    $this->displayField('name');
    $this->primaryKey('id');
    $this->addBehavior('Timestamp');
    $this->belongsTo('Users', [
        'foreignKey' => 'user_id',

    ]);
    $this->belongsTo('Businesses', [
        'foreignKey' => 'hotel_id',
        'joinType' => 'INNER'
    ]);
    $this->belongsToMany('Courses', [
        'foreignKey' => 'employee_id',
        'targetForeignKey' => 'course_id',
        'joinTable' => 'courses_employees'
    ]);
}

用户模型

public function initialize(array $config)
{
    $this->table('users');
    $this->displayField('email');
    $this->primaryKey('id');
    $this->addBehavior('Timestamp');
    $this->belongsTo('Roles', [
        'foreignKey' => 'role_id'
    ]);
    $this->hasOne('Employees', [
        'foreignKey' => 'user_id'
    ]);
    $this->hasOne('Businesses', [
        'foreignKey' => 'user_id'
    ]);
}

0 个答案:

没有答案