Cakephp 3 - belongsToMany with _joinData

荒凉一梦 提交于 2020-01-05 08:04:33

问题


I try to realize a bolongsToMany association with additional data in the join table. The join table has columns for the foreign keys and an additional column 'context'

articlesController:
$article = $this->Articles->patchEntity($article, $this->request->getData());
debug($article);die;


and in a Plugin-Behavior:
public function beforeMarshal(Event $event, ArrayObject $data, ArrayObject $options)
{
  $data['Categories.Categories'] = ['id' => '1', '_joinData' => ['context' => 'Tag']];
  debug($data);
}

I expect the context beeing saved in the join table, but it doesn't. The debgger says:

/plugins/Categories/src/Model/Behavior/CategorizeableBehavior.php (line 37)
object(ArrayObject) {
    name => 'dfa'
    description => 'er'
    Categories.Categories => [
        'id' => '1',
        '_joinData' => [
            'context' => 'Tag'
        ]
    ]
}
/src/Controller/ArticlesController.php (line 56)
object(App\Model\Entity\Article) {

    'name' => 'dfa',
    'description' => 'er',
    '[new]' => true,
    '[accessible]' => [
        'name' => true,
        'description' => true,
        'created' => true,
        'modified' => true
    ],
    '[dirty]' => [
        'name' => true,
        'description' => true
    ],
    '[original]' => [],
    '[virtual]' => [],
    '[errors]' => [],
    '[invalid]' => [],
    '[repository]' => 'Articles'

}

Where's my category and context. What's wrong with my code?


回答1:


If you want to attach join data it needs to be in a nested array.

$data['Categories.Categories'] = [
      ['id' => '1', '_joinData' => ['context' => 'Tag']]
];

It has to be a nested array so that you could attached multiple records (if you wanted too).



来源:https://stackoverflow.com/questions/47924459/cakephp-3-belongstomany-with-joindata

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!