CakePHP 3:如何更新外键?

CakePHP 3: How to update foreignKey?

我使用 BlueImp jQuery 插件在以下场景中上传多张图片:

  1. 用户打开添加或编辑相册页面,select 图像和过程通过 ajax 方法上传。这项工作很好,图像数据(名称、尺寸、型号、字段等)存储在相关图像 table 中,没有外键。

  2. Ajax return 最近上传图片的id,js为该文件创建(字幕,位置)输入。

  3. 用户填写其他表单字段,然后点击提交。

问题,如果用户创建新相册或 edit/update 存在不包含图像的相册,应用程序不会为新图像更新外键。但是如果相册包含图像,并且用户将新图像添加到相册,保存后 post cakephp 添加/更新外键到新图像记录。

调试输出:

// first time add images, does not update FK
[
    'name' => 'A4',
    'images' => [
        (int) 116 => [
            'caption' => '',
            'position' => '1',
            'id' => '116'
        ]
    ],
    'id' => '4',
    'user_id' => '1',
    'active' => '1'
]

// album has one image, we add new one, CakePHP Update FK for new images
[
    'name' => 'A4',
    'images' => [
        (int) 117 => [
            'caption' => '',
            'position' => '1',
            'id' => '117'
        ],
        (int) 118 => [
            'caption' => '',
            'position' => '2',
            'id' => '118'
        ]
    ],
    'id' => '4',
    'user_id' => '1',
    'active' => '1'
]

AlbumsController添加方法:

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

专辑Table:

    $this->hasMany('Images', [
        'foreignKey' => 'foreign_key',
        'conditions' => [
            'Images.model' => 'Albums',
            'Images.field' => 'upload'
        ],
        'sort' => ['Images.position'  => 'ASC']
    ]);

图片 Table:

    $this->belongsTo('Albums', [
        'foreignKey' => 'foreign_key',
        'joinType' => 'INNER'
    ]);

我在 cakephp 2 应用程序中使用相同的方法,并且工作没有问题。

视频:http://screencast-o-matic.com/watch/cDhYYOinCX

问:如何更新foreignKey?

我不确定这种方法是否正确,但它对我有用。

专辑表

public function afterSave(Event $event, Entity $entity, ArrayObject $options)
{
   if (isset($entity)) {
        $images = TableRegistry::get('Images');
        $images->query()
            ->update()
            ->set(['foreign_key' => $entity->id])
            ->where([
                'foreign_key IS NULL',
                'model' => 'Albums'
                ])
            ->execute();// conditions
           }
}