克鲁德插件 - 保存多对多关联



我目前正在尝试使用FriendsOfCake/crud插件保存相关数据。但是,我似乎无法弄清楚如何将关系保存到具有多对多关联的关系。我有以下代码:

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

我有一个相册和用户表,它们通过一个名为 UsersAlbums 的连接表连接(album_id和user_id作为复合主键(。当我执行代码时,相册已正确存储,但未保存 UsersAlbums 表中的关联。 我目前正在事务中执行两个数据库调用(一个用于保存相册,另一个用于保存与用户的关联(以保存行。由于效率低下,有没有人有一些建议/方向如何使用 crud 插件解决这个问题?

试试这个 8(

namespace AppController;
use AppControllerAppController;
use CakeEventEvent;
class AlbumsController extends AppController
{
    public function initialize()
    {
        parent::initialize();
        $this->viewBuilder()->className('CrudViewViewCrudView');
        $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();
    }
}

最新更新