关联数据未保存在cakephp 3.6中

时间:2018-07-21 13:14:23

标签: php cakephp associations cakephp-3.0

我想使用cakephp 3.6中的关联将数据保存在多个表中。我有两个表部门和用户。 关系是

  • 部门有很多用户
  • 用户属于部门

这是我的代码

DepartmentsController

<?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\Event\Event;
class DepartmentsController extends AppController
{
    public function register()
    {
        $this->loadModel('Departments');
        $department = $this->Departments->newEntity();
        if ($this->request->is('post')) {
            $department = $this->Departments->patchEntity($department, $this->request->data, [
                'associated' => [
                    'Users'
                ]
            ]);
            if ($this->Departments->save($department)){
                $resultJ = json_encode(['status' => true, 'result' => 'You are registered and can login']);
            } 
            else {
                $resultJ = json_encode(['status' => false, 'result' => 'Something went wrong! Please try again']);
            }
            $this->response->type('json');
            $this->response->body($resultJ);
            return $this->response;

        }
        $this->set(compact('department', 'user'));
        $this->set('_serialize', ['department']);
        $this->viewBuilder()->setLayout('login');
    }
}

register.ctp

<?php
$this->Form->setTemplates([
    'inputContainer' => '{{content}}'
]);
echo $this->Form->create($department, ['class' => 'registration-form']);
?>
    <div class="alert alert-danger display-hide">
        <button class="close" data-close="alert"></button>
        <span><?= __('Please fill the required fields.') ?> </span>
    </div>
    <?= $this->Flash->render() ?>
    <div class="row">
        <div class="col-xs-12 col-md-6">
            <?= $this->Form->control('users.0.first_name', [
                'label' => false, 
                'class' => 'form-control form-control-solid placeholder-no-fix form-group',
                'placeholder' => __('First Name'),
                'autocomplete' => 'off',
            ]); ?>
        </div>
        <div class="col-xs-12 col-md-6">
            <?= $this->Form->control('users.0.last_name', [
                'label' => false, 
                'class' => 'form-control form-control-solid placeholder-no-fix form-group',
                'placeholder' => __('Last Name'),
                'autocomplete' => 'off',
            ]); ?>
        </div>
        <div class="col-xs-12 col-md-6">
            <?= $this->Form->control('users.0.email', [
                'label' => false, 
                'class' => 'form-control form-control-solid placeholder-no-fix form-group',
                'placeholder' => __('E-mail'),
                'autocomplete' => 'off',
            ]); ?>
        </div>
        <div class="col-xs-12 col-md-6">
            <?= $this->Form->control('users.0.password', [
                'label' => false, 
                'class' => 'form-control form-control-solid placeholder-no-fix form-group',
                'placeholder' => __('Password'),
                'autocomplete' => 'off',
                'type' => 'password'
            ]); ?>
        </div>
        <div class="col-xs-12 col-md-6">
            <?= $this->Form->control('name', [
                'label' => false,
                'id' => 'domain_name',
                'class' => 'form-control form-control-solid placeholder-no-fix form-group',
                'placeholder' => __('Department Name'),
                'autocomplete' => 'off',
            ]); ?>
        </div>
        <div class="col-xs-12 col-md-6">
            <?= $this->Form->control('domain', [
                'label' => false, 
                'id' => 'domain_slug',
                'class' => 'form-control form-control-solid placeholder-no-fix form-group',
                'placeholder' => __('Domain Name'),
                'autocomplete' => 'off',
            ]); ?>
        </div>
    </div>
    <div class="row">
        <div class="col-sm-4">
            <div class="forgot-password-link">
                <?= $this->Html->link(__('Already have an account?'), '/', ['class' => 'forget-password', 'id' => 'forget-password']) ?>
            </div>
        </div>
        <div class="col-sm-8 text-right">
            <?= $this->Form->button(__('Sign Up'), ['class' => 'btn blue']) ?>
        </div>
    </div>
<?= $this->Form->end() ?>

DepartmentsTable.php

<?php
namespace App\Model\Table;

use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
class DepartmentsTable extends Table
{
    public function initialize(array $config)
    {
        parent::initialize($config);

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

        $this->addBehavior('Timestamp');
        $this->hasMany('Users', [
            'foreignKey' => 'department_id'
        ]);
    }

    public function validationDefault(Validator $validator)
    {
        $validator
            ->uuid('id')
            ->allowEmpty('id', 'create');

        $validator
            ->scalar('org_no')
            ->maxLength('org_no', 35)
            ->allowEmpty('org_no');

        $validator
            ->boolean('active')
            ->requirePresence('active', 'create')
            ->notEmpty('active');

        return $validator;
    }

    public function buildRules(RulesChecker $rules)
    {
        $rules->add($rules->existsIn(['department_id'], 'Users'));
        return $rules;
    }
}

UsersTable.php

<?php
namespace App\Model\Table;

use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
class UsersTable extends Table
{
    public function initialize(array $config)
    {
        parent::initialize($config);

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

        $this->addBehavior('Timestamp');

        $this->belongsTo('Departments', [
            'foreignKey' => 'department_id',
        ]);
    }
   public function validationDefault(Validator $validator)
    {
        $validator
            ->uuid('id')
            ->allowEmpty('id', 'create');
        return $validator;
    }


    public function buildRules(RulesChecker $rules)
    {
        $rules->add($rules->isUnique(['email']));
        return $rules;
    }
}

实体模型

Department.php

<?php
namespace App\Model\Entity;

use Cake\ORM\Entity;

class Department extends Entity
{
    protected $_accessible = [
        'name' => true,
        'org_no' => true,
        'domain' => true,
        'active' => true,
        'created' => true,
        'modified' => true,
        'user' => true
    ];
}

问题在于数据仅保存到部门表中,而不保存在用户表中。如何使用cakephp 3.6关联将数据保存在用户表中?

2 个答案:

答案 0 :(得分:1)

在部门实体模型中,您使用“用户”获取可访问的数据。对于hasMany关系,必须在“用户”中进行更改。尝试使用“用户” => true

<?php
namespace App\Model\Entity;

use Cake\ORM\Entity;

class Department extends Entity
{
    protected $_accessible = [
    'name' => true,
    'org_no' => true,
    'domain' => true,
    'active' => true,
    'created' => true,
    'modified' => true,
    'users' => true
    ];
}

答案 1 :(得分:0)

$department = $this->Departments->newEntity();
debug($department); // <<<<<<<< DEBUG 1
        if ($this->request->is('post')) {
            // Should be patchEntities() ?
            $department = $this->Departments->patchEntity($department, $this->request->data, [
                'associated' => [
                    'Users'
                ]
            ]);
           debug($department); // <<<<<<<< DEBUG 2 AND Compare with DEBUG 1

阅读:

https://book.cakephp.org/3.0/en/orm/saving-data.html#saving-multiple-entities