简体   繁体   English

如何在cakephp 3中保存数据并保存到joinTable

[英]How to save data in cakephp 3 with saving to joinTable

I am new to php frameworks and I've started to learn cakephp few days ago, but even after reading cakephp cookbook about saving belongsToMany associations I still don't know how to implement it in my situation. 我是php框架的新手,几天前我已经开始学习cakephp,但是即使在阅读了关于保存elseToMany关联的cakephp食谱之后,我仍然不知道如何在我的情况下实现它。

I have three tables: 我有三个表:
clients: 客户:
id | id | firstname | 名| lastname | 姓| phone | 电话| email 电子邮件
interests: 利益:
id | id | text | 文字| comment | 评论| status_id | status_id | created_at created_at
clients_interests: clients_interests:
client_id | client_id | interest_id interest_id

Models and entities were baked so I don't think it's something wrong there, but here is the code: ClientsTable.php 模型和实体已经出炉了,所以我认为那里没什么问题,但这是代码: ClientsTable.php

class ClientsTable extends Table
{            
    public function initialize(array $config)
    {
        parent::initialize($config);

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

        $this->belongsToMany('Interests', [
            'foreignKey' => 'client_id',
            'targetForeignKey' => 'interest_id',
            'joinTable' => 'clients_interests'
        ]);
    }

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

        $validator
            ->scalar('firstname')
            ->maxLength('firstname', 64)
            ->requirePresence('firstname', 'create')
            ->allowEmptyString('firstname', false);

        $validator
            ->scalar('middlename')
            ->maxLength('middlename', 64)
            ->allowEmptyString('middlename');

        $validator
            ->scalar('lastname')
            ->maxLength('lastname', 64)
            ->requirePresence('lastname', 'create')
            ->allowEmptyString('lastname', false);

        $validator
            ->scalar('phone')
            ->maxLength('phone', 24)
            ->requirePresence('phone', 'create')
            ->allowEmptyString('phone', false)
            ->add('phone', 'unique', ['rule' => 'validateUnique', 'provider' => 'table']);

        $validator
            ->email('email')
            ->allowEmptyString('email');

        return $validator;
    }

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

        return $rules;
    }
}

InterestsTable.php InterestsTable.php

class InterestsTable extends Table
{
    public function initialize(array $config)
    {
        parent::initialize($config);

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

        $this->belongsTo('Statuses', [
            'foreignKey' => 'status_id',
            'joinType' => 'INNER'
        ]);
        $this->belongsToMany('Clients', [
            'foreignKey' => 'interest_id',
            'targetForeignKey' => 'client_id',
            'joinTable' => 'clients_interests'
        ]);
    }


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

        $validator
            ->scalar('text')
            ->maxLength('text', 128)
            ->requirePresence('text', 'create')
            ->allowEmptyString('text', false);

        $validator
            ->scalar('comment')
            ->maxLength('comment', 128)
            ->allowEmptyString('comment');

        $validator
            ->date('created_at')
            ->requirePresence('created_at', 'create')
            ->allowEmptyDate('created_at', false);

        return $validator;
    }


    public function buildRules(RulesChecker $rules)
    {
        $rules->add($rules->existsIn(['status_id'], 'Statuses'));

        return $rules;
    }


    public function getAll($id)
    {
        $connection = ConnectionManager::get('default');
        $results = $connection
            ->execute('SELECT i.*, s.name status_name, s.classname status_classname FROM interests i INNER JOIN clients_interests ci ON ci.interest_id=i.id AND ci.client_id=:client_id INNER JOIN statuses s ON i.status_id=s.id ORDER BY created_at DESC;', ['client_id' => $id])
            ->fetchAll('assoc');
        return $results;
    }
}

ClientsInterestsTable.php ClientsInterestsTable.php

class ClientsInterestsTable extends Table
{            
    public function initialize(array $config)
    {
        parent::initialize($config);

        $this->setTable('clients_interests');
        $this->setDisplayField('client_id');
        $this->setPrimaryKey(['client_id', 'interest_id']);

        $this->belongsTo('Clients', [
            'foreignKey' => 'client_id',
            'joinType' => 'INNER'
        ]);
        $this->belongsTo('Interests', [
            'foreignKey' => 'interest_id',
            'joinType' => 'INNER'
        ]);
    }


    public function buildRules(RulesChecker $rules)
    {
        $rules->add($rules->existsIn(['client_id'], 'Clients'));
        $rules->add($rules->existsIn(['interest_id'], 'Interests'));

        return $rules;
    }
}

Client entity - Client.php 客户实体-Client.php

class Client extends Entity
{         
    protected $_accessible = [
        'firstname' => true,
        'middlename' => true,
        'lastname' => true,
        'phone' => true,
        'email' => true
    ];
}

Interest entity - Interest.php 兴趣实体-Interest.php

class Interest extends Entity
{          
    protected $_accessible = [
        'text' => true,
        'comment' => true,
        'status_id' => true,
        'created_at' => true,
        'clients_interest' => true,
        'status' => true
    ];
}

ClientsInterests entity - ClientsInterests.php ClientsInterests实体-ClientsInterests.php

class ClientsInterest extends Entity
{

    protected $_accessible = [
        'client' => true,
        'interest' => true
    ];
}

And then in my controller I get all the data from a form. 然后在我的控制器中,我从表单中获取所有数据。 Interest entity after patchEntity() gets all its data besides client data for joinTable. patchEntity()之后的兴趣实体获取除joinTable的客户端数据以外的所有数据。 And after save method new interest in interests table is created but there is no new row in clients_interests table. 在保存方法之后,在兴趣表中创建了新的兴趣,但是在clients_interests表中没有新的行。 I've tried a lot of things from stackoverflow but it didn't work because I can't understand the mechanism of saving associated data even after reading the manual. 我已经尝试了stackoverflow的很多方法,但是它没有用,因为即使阅读了手册,我也无法理解保存关联数据的机制。 Could anyone explain me in simple words how to save belongsToMany associated data? 谁能用简单的词解释我如何保存belongsToMany相关数据? Here is the code of my save method in InterestsController.php: 这是我在InterestsController.php中保存方法的代码

public function add()
    {
        $this->request->allowMethod(['ajax', 'post']);
        $this->response->withDisabledCache();

        $interest = $this->Interests->newEntity();
        $interest = $this->Interests->patchEntity($interest, $this->request->getData(), 
            ['associated'=>['Clients._joinData']]
        );       

        if($this->Interests->save($interest)) {
            $result = ['error' => null, 'error_text' => 'SUCCESSFUL'];
        } else {
            $result = ['error' => null, 'error_text' => 'ERRORS ERRORS ERRORS'];
        }

        $result = ['error' => null, 'error_text' => 'ERRORS ERRORS ERRORS'];
        $this->set('result', $result);
        $this->set('_serialize', ['result']);
    }

And in my template I use this input for getting client_id: 在我的模板中,我使用以下输入获取client_id:

<?php echo $this->Form->control('clients.0.client_id', ['hidden', 'type'=>'text','id'=>'client-id', 'class'=>'form-control']); ?>

Request data looks like this: request data 请求数据如下所示: 请求数据

And Interest entity after patchEntity() looks like this: Interest entity patchEntity()之后的兴趣实体如下所示: 兴趣实体

If you want to add an 'interest', I think your request data should look differently. 如果您想添加一个“兴趣”,我认为您的请求数据应该看起来有所不同。

Here is an example, but sorry, I haven't tested it, it's made so you get the idea : you have to tell CakePHP you want to create a Interest entity, and inside add a Client information (just like in the "Converting BelongsToMany Data" in "Saving Data" of book.cakephp.org/3.0/en/orm/saving-data.html ). 这是一个示例,但是很抱歉,我尚未对其进行测试,因此您已经明白了:您必须告诉CakePHP您要创建一个Interest实体,然后在其中添加一个Client信息(就像在“转换BelongsToMany中数据”中的book.cakephp.org/3.0/en/orm/saving-data.html )。

$data = [
_csrfToken => "...",
'interests' => [
    'text' => 'texttext',
    'comment' => '',
    'created_at' => '2019-01-10',
    'status_id' => 2,
    'clients' => [
        '_ids' => [0],
   ]
];

Personally, I learnt a lot looking at the requests generated through the Form Helper from the automatically baked templates. 就个人而言,我了解了很多有关自动烘焙模板中通过Form Helper生成的请求的信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM