CakePHP 3.X 多模型关联

CakePHP 3.X Multiple Model association

目前我有 'posts' 和 'users' 模型与 'attachments' 模型相关联,一切正常,因为我需要在每个表单中放置一个隐藏的输入告诉 CakePHP我要使用哪个模型,就像下面的代码:

<?= $this->Form->create($post); ?>
<fieldset>
    <legend>Create a new Post</legend>

    <?php
        echo $this->Form->input('title');
        echo $this->Form->input('content');
        echo $this->Form->hidden('attachments.0.model', ['default' => 'Post']);
        echo $this->Form->control('attachments.0.image_url');
        echo $this->Form->hidden('attachments.1.model', ['default' => 'Post']);
        echo $this->Form->control('attachments.1.image_url');
    ?>
</fieldset>
<?= $this->Form->button(__('Save Post')); ?>
<?= $this->Form->end(); ?>

有没有办法告诉 Cake 我要为每个 model/controller 使用哪个 Attachment.model?或者这是正确的方法?

您可以使用相应的 table 类 beforeSave and/or beforeMarshal events/callbacks 修改附件数据table(型号),即注入table(型号)名称。

根据您想要应用的时间,您可以只使用它们(only/before 编组 > 使用 beforeMarshal,仅保存 > 使用 beforeSave),甚至两者都使用。

这是一个在编组和保存阶段无条件地注入当前 table 名称的基本示例:

use Cake\Datasource\EntityInterface;
use Cake\Event\Event;

// ...

public function beforeMarshal(Event $event, \ArrayObject $data, \ArrayObject $options)
{
    if (isset($data['attachments']) &&
        is_array($data['attachments'])
    ) {
        $alias = $this->registryAlias();
        foreach ($data['attachments'] as &$attachment) {
            $attachment['model'] = $alias;
        }
    }
}

public function beforeSave(Event $event, EntityInterface $entity, \ArrayObject $options)
{
    $attachments = $entity->get('attachments');
    if (is_array($attachments)) {
        $alias = $this->registryAlias();
        foreach ($attachments as $attachment) {
            $attachment->set('model', $alias);
        }
    }
}

另见