2017-03-22 126 views
1

目前我有一个'贴子'和'用户'模型关联到'附件'模型,一切工作完全胜任,因为我需要把每个窗体的隐藏输入告诉CakePHP模型我要去使用,就像下面的代码:CakePHP 3.X多个模型关联

<?= $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(); ?> 

有没有办法告诉的蛋糕Attachment.model我将使用每个模型/控制器?或者这是做到这一点的正确方法?

+0

根据[为关联数据创建输入](https://book.cakephp.org/3.0/en/views/helpers/form.html#creating-inputs-for-associated-data),您可以创建输入相关数据如下:'echo $ this-> Form-> control('tags.0.id');'尽管我认为我误解了这个问题。您正在尝试编辑与“Posts”关联的“附件”?如果是这样,我可以写一个更好的解释。 – Sevvlor

回答

1

您可以使用相应的表类beforeSave和/或beforeMarshal事件/回调来修改与当前表(模型)相关的附件数据,即注入表(模型)的名称。

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

下面是无论在编组无条件注入当前表名一个基本的例子,以及保存阶段:

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); 
     } 
    } 
} 

参见

+0

完美适合我,谢谢 – noeyeat