簡體   English   中英

如何在cakephp 3中保存數據並保存到joinTable

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

我是php框架的新手,幾天前我已經開始學習cakephp,但是即使在閱讀了關於保存elseToMany關聯的cakephp食譜之后,我仍然不知道如何在我的情況下實現它。

我有三個表:
客戶:
id | 名| 姓| 電話| 電子郵件
利益:
id | 文字| 評論| status_id | created_at
clients_interests:
client_id | interest_id

模型和實體已經出爐了,所以我認為那里沒什么問題,但這是代碼: 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

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

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.php

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

興趣實體-Interest.php

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

ClientsInterests實體-ClientsInterests.php

class ClientsInterest extends Entity
{

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

然后在我的控制器中,我從表單中獲取所有數據。 patchEntity()之后的興趣實體獲取除joinTable的客戶端數據以外的所有數據。 在保存方法之后,在興趣表中創建了新的興趣,但是在clients_interests表中沒有新的行。 我已經嘗試了stackoverflow的很多方法,但是它沒有用,因為即使閱讀了手冊,我也無法理解保存關聯數據的機制。 誰能用簡單的詞解釋我如何保存belongsToMany相關數據? 這是我在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']);
    }

在我的模板中,我使用以下輸入獲取client_id:

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

請求數據如下所示: 請求數據

patchEntity()之后的興趣實體如下所示: 興趣實體

如果您想添加一個“興趣”,我認為您的請求數據應該看起來有所不同。

這是一個示例,但是很抱歉,我尚未對其進行測試,因此您已經明白了:您必須告訴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],
   ]
];

就個人而言,我了解了很多有關自動烘焙模板中通過Form Helper生成的請求的信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM