Cakephp更新另一个关于字段更改的表

时间:2018-06-05 14:07:18

标签: cakephp-3.x

我有2个表:客户和资产分配。 客户表有一个字段:is_active。

在编辑模式下,当is_active从TRUE更改为FALSE时,我需要通过为所选客户端的所有assets_assignations设置end_date = TODAY来更新Assignations表。

AssetsAssignations包含以下字段:(id,asset_id,client_id,room_id,ip_address,starting_date,ending_date)。在AssetsAssignationsTable中:

public function initialize(array $config)
{
    parent::initialize($config);

    $this->table('assets_assignations');
    $this->displayField('id');
    $this->primaryKey('id');

    $this->belongsTo('Assets', [
        'foreignKey' => 'asset_id'
    ]);
    $this->belongsTo('Clients', [
        'foreignKey' => 'client_id'
    ]);
    $this->belongsTo('Rooms', [
        'foreignKey' => 'room_id'
    ]);

}

在ClientsTable中:

public function initialize(array $config)
{
    parent::initialize($config);

    $this->table('clients');
    $this->DisplayField('full_name');
    $this->primaryKey('id');

    $this->hasMany('AssetsAssignations', [
        'foreignKey' => 'client_id'
    ]);

    ....
}

这是我对客户的编辑功能:

public function edit($id = null)
{
    $client = $this->Clients->get($id, [
        'contain' => []
    ]);
    if ($this->request->is(['patch', 'post', 'put'])) {
        $client = $this->Clients->patchEntity($client, $this->request->data);
        if ($this->Clients->save($client)) {
            $this->Flash->success(__('The client has been saved.'));

            return $this->redirect(['action' => 'index']);
        }
        $this->Flash->error(__('The client could not be saved. Please, try again.'));
    }
    $clientTypes = $this->Clients->ClientTypes->find('list', ['limit' => 200]);
    $this->set(compact('client', 'clientTypes'));
    $this->set('_serialize', ['client']);
}

1 个答案:

答案 0 :(得分:1)

我的建议:

在ClientsTable.php中,添加

use ArrayObject;
use Cake\Datasource\EntityInterface;
use Cake\Event\Event;
use Cake\I18n\FrozenDate;

/**
 * Perform additional operations after it is saved.
 *
 * @param \Cake\Event\Event $event The afterSave event that was fired
 * @param \Cake\Datasource\EntityInterface $entity The entity that was saved
 * @param \ArrayObject $options The options passed to the save method
 * @return void
 */
public function afterSave(Event $event, EntityInterface $entity, ArrayObject $options) {
    // For CakePHP 3.4.3 or later, use isDirty instead of dirty
    if (!$entity->isNew() && $entity->dirty('is_active') && !$entity->is_active) {
        $this->AssetsAssignations->updateAll(['end_date' => FrozenDate::now()], ['client_id' => $entity->id]);
    }
}

通过将此代码放在afterSave事件处理程序中,可以确保在is_active标志更改为false时,无论该更改是来自编辑页面还是其他位置,都会发生这种情况。 (现在可能没有其他任何地方可以更新此内容,但是如果稍后会添加某些此类内容,这将在未来证明。)