【问题标题】:Crud plugin - save many-to-many associationCrud 插件 - 保存多对多关联
【发布时间】:2017-04-13 20:35:35
【问题描述】:

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

$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]
    ];
});

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

【问题讨论】:

    标签: cakephp cakephp-3.0


    【解决方案1】:

    试试这个 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();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-09
      • 1970-01-01
      • 1970-01-01
      • 2018-01-13
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多