我目前正在尝试使用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插件解决这个问题?
答案 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();
}
}