2017-01-28 17 views
0

У меня есть таблица nodes и таблица nodes_nodes.cakephp 3 сохранение саморекламы принадлежитToMany

nodes table +----+--------+ | id | name | +----+--------+ | 1 | Node1 | | 2 | Node2 | | 3 | Node3 | | 4 | Node4 | | 5 | Node5 | +----+--------+

nodes_nodes table +----+----------------+---------------+ | id | parent_node_id | child_node_id | +----+----------------+---------------+ | 1 | 2 | 3 | | 2 | 1 | 4 | | 3 | 1 | 5 | +----+----------------+---------------+

Узел может иметь один или несколько родителей и одного или более Childs

NodesTable.php:

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

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

    $this->addBehavior('Timestamp'); 

    $this->belongsToMany('ChildNodes', [ 
     'className' => 'Nodes', 
     'joinTable' => 'nodes_nodes', 
     'foreignKey' => 'parent_node_id', 
     'targetForeignKey' => 'child_node_id' 
    ]); 

    $this->belongsToMany('ParentNodes', [ 
     'className' => 'Nodes', 
     'joinTable' => 'nodes_nodes', 
     'foreignKey' => 'child_node_id', 
     'targetForeignKey' => 'parent_node_id' 
    ]); 

} 

Node.php

class Node extends Entity 
{ 

    protected $_accessible = [ 
     '*' => true, 
     'id' => false, 
     'ParentNodes' => true, 
     'ChildNodes' => true, 
     '_joinData' => true, 
    ]; 
} 

NodesController.php

public function add() 
{ 
    $node = $this->Nodes->newEntity(); 
    if ($this->request->is('post')) { 
     $node = $this->Nodes->patchEntity($node, $this->request->data); 
     debug($node); 
     if ($this->Nodes->save($node)) { 
      $this->Flash->success(__('The node has been saved.')); 

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

add.ctp форма:

<?= $this->Form->create($node) ?> 
<fieldset> 
    <legend><?= __('Add Node') ?></legend> 
    <?php 
     echo $this->Form->input('name'); 
     echo $this->Form->input('ParentNodes._ids', ['options' => $nodes]); 
     echo $this->Form->input('ChildNodes._ids', ['options' => $nodes]); 
    ?> 
</fieldset> 
<?= $this->Form->button(__('Submit')) ?> 
<?= $this->Form->end() ?> 

Вывод $ узла объекта отладки в оных() функции:

object(App\Model\Entity\Node) { 

    'name' => 'Node6', 
    'ParentNodes' => [ 
     '_ids' => [ 
      (int) 0 => '15', 
      (int) 1 => '12' 
     ] 
    ], 
    'ChildNodes' => [ 
     '_ids' => [ 
      (int) 0 => '13' 
     ] 
    ], 
    '[new]' => true, 
    '[accessible]' => [ 
     '*' => true, 
     'ParentNodes' => true, 
     'ChildNodes' => true, 
     '_joinData' => true 
    ], 
    '[dirty]' => [ 
     'name' => true, 
     'ParentNodes' => true, 
     'ChildNodes' => true 
    ], 
    '[original]' => [], 
    '[virtual]' => [], 
    '[errors]' => [], 
    '[invalid]' => [], 
    '[repository]' => 'Nodes' 

} 

Когда я сохраняю новый узел ассоциация не сохраняется. Я попытался добавить ['associated' => ['ParentNodes', 'ChildNodes']] на $this->Nodes->save() без успеха

ответ

0

Вы не соблюдаете правила именования правильно. Имена свойств для ассоциаций belongsToMany по умолчанию строчные, подчеркнутые множественные варианты ассоциативных псевдонимов, то есть parent_nodes и child_nodes. В случае необходимости это можно изменить с помощью опции ассоциации propertyName.

echo $this->Form->input('parent_nodes._ids', ['options' => $nodes]); 
echo $this->Form->input('child_nodes._ids', ['options' => $nodes]); 

Также нет необходимости добавлять свойства к $_accessible, если вы установили * к true, поскольку это позволяет всему быть масса назначен.

Смотрите также

+0

И это было так просто ... Я была так сосредоточена на модели и контроллер, я не думаю, чтобы проверить надлежащим образом Форма. Свойства в '$ _accessible' были отчаянным движением из другого найденного мной стека. В любом случае, большое спасибо! – alloa