chishiki
chishiki

Reputation: 702

Crud plugin - save many-to-many association

I'm currently trying to save associated data with the FriendsOfCake/crud plugin. However, I can't seem to figure out how to save a relation to has a many-to-many association. I have the following code:

$this->Crud->action()->saveOptions(['atomic' => false]);
$this->Crud->listener('relatedModels')->relatedModels(true);
$this->Crud->on('beforeSave', function(\Cake\Event\Event $event){
    $event->subject->entity->Users = [
         ['user_id' => $this->userId]
    ];
});

I have an Albums and Users table that are connected through a join table called UsersAlbums (with album_id and user_id as composite primary key). When I execute the code, the album is stored correctly but the association in the UsersAlbums table isn't saved. I'm currently perform two database calls (one for saving the album and one for saving the association with the user) in a transaction to save the rows. As this is inefficient, is there anyone that does have some suggestions/directions how to solve this by using the crud plugin?

Upvotes: 1

Views: 499

Answers (1)

Zagat Null
Zagat Null

Reputation: 26

Try this 8)

namespace App\Controller;

use App\Controller\AppController;
use Cake\Event\Event;

class AlbumsController extends AppController
{
    public function initialize()
    {
        parent::initialize();
        $this->viewBuilder()->className('CrudView\View\CrudView');
        $this->loadComponent('Crud.Crud', [
            'actions' => [
                'Crud.Index',
                'Crud.View',
                'Crud.Add',
                'Crud.Edit',
                'Crud.Delete',
            ],
            'listeners' => [
                'CrudView.View',
                'Crud.RelatedModels',
                'Crud.Redirect',
            ],
        ]);
        $this->Crud->action()->config('scaffold.tables_blacklist', [
            'phinxlog',
            'sessions',
            'users_albums',
        ]);
    }

    public function beforeFilter(Event $event)
    {
        parent::beforeFilter($event);
        $this->Auth->allow([
            'index',
            'view',
        ]);
    }

    public function add()
    {
        $action = $this->Crud->action();
        $action->config('scaffold.fields', [
            'title',
            'description',
        ]);
        $action->config('scaffold.relations', ['Users']);
        $this->Crud->on('beforeSave', function ($event) {
            $event->getSubject()->entity->user_id = $this->Auth->user('id');
        });
        return $this->Crud->execute();
    }
}

Upvotes: 1

Related Questions