2017-04-13 73 views
0

我正在嘗試使用FriendsOfCake/crud插件保存關聯的數據。但是,我似乎無法弄清楚如何保存一個關係以建立多對多關聯。我有以下代碼: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] 
    ]; 
}); 

我具有通過一個連接表稱爲UsersAlbums連接(與album_id和USER_ID作爲複合主鍵)的相冊和用戶表。當我執行代碼時,專輯將被正確存儲,但UsersAlbums表中的關聯不會被保存。我目前正在執行兩個數據庫調用(一個用於保存相冊,另一個用於保存與用戶的關聯)以保存行。由於這是效率低下,有沒有人有一些建議/方向如何通過使用crud插件來解決這個問題?

回答

0

試試這個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(); 
    } 
}