CakePHP 3 belongsToMany example

http://stackoverflow.com/questions/26023045/using-belongstomany-association-in-cakephp-3

I have three tables categories, articles, articles_categories
 First is the articles table:

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

    $this->belongsToMany('Categories',
        [
            'targetForeignKey' => 'category_id',
            'foreignKey' => 'article_id',
            'joinTable' => 'articles_categories',
        ]);

}

Next, the Categories table:

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

        $this->belongsToMany('Articles',
            [
                'targetForeignKey' => 'article_id',
                'foreignKey' => 'category_id',
                'joinTable' => 'articles_categories',
            ]);
    }

Now, the ContinuitiesController add() function:

$article = $this->Articles->newEntity();
if ($this->request->is('post')) {
   
    $this->Articles->patchEntity($article, $this->request->data(), ['associated'=>['Categories']]);
    if ($result = $this->Articles->save($article, ['associated'=>['Categories']])) {
        $this->Flash->success(__('The article has been updated.'));
        return $this->redirect(['action' => 'index']);
    }

    $this->Flash->error(__('Unable to add your article.'));
}

$categoriesTable = TableRegistry::get('Categories');
$categories = $categoriesTable->find('list');
$this->set('categories', $categories);

$this->set('form_title', 'Add Article');
$this->set('article', $article);
$this->render('form');

 Now, the ContinuitiesController edit() function:

 $this->set('form_title', 'Edit Article');

$article = $this->Articles->find()->where(['id'=>$id])->contain('Categories')->first();

if ($this->request->is(['post', 'put'])) {
    $this->Articles->patchEntity($article, $this->request->data(), ['associated'=>['Categories']]);
    if ($result = $this->Articles->save($article, ['associated'=>['Categories']])) {
        $this->Flash->success(__('The article has been updated.'));
        return $this->redirect(['action' => 'index']);
    }
    $this->Flash->error(__('Unable to update the article.'));
}

$categoriesTable = TableRegistry::get('Categories');
$categories = $categoriesTable->find('list');
$this->set(compact('article', 'categories'));

$this->render('form');

And finally, the edit.ctp
echo $this->Form->input('categories._ids', ['options' => $categories, 'multiple'=>true]);