我正在使用PageKit CMS。我有2个表与多对多关系(项目和类型)。
物品型号:
class Item implements \JsonSerializable
{
...
/**
* @ManyToMany(targetEntity="Type", tableThrough="@prefix_item_type", keyThroughFrom="item_id", keyThroughTo="type_id")
*/
public $types;
...
}
输入型号:
class Type implements \JsonSerializable
{
...
/**
* @ManyToMany(targetEntity="Item", tableThrough="@prefix_item_type", keyThroughFrom="type_id", keyThroughTo="item_id")
*/
public $items;
...
}
在项目编辑页面的后端界面中,我创建了所有类型的多选。当我发送项目保存请求时,我会输入类型ID。
我的保存项目方法看一下:
public function saveAction($data, $id = 0, $selected_types = [])
{
/*
* $selected_types = array(2) {
* [0]=>int(1)
* [1]=>int(2)
* }
*/
if (!$id || !$item = Item::query()->related(['types'])) {
if ($id) {
App::abort(404, __('Item not found'));
}
$item = Item::create();
}
if (!$data['slug'] = App::filter($data['slug'] ?: $data['title'], 'slugify')) {
App::abort(400, __('Invalid alias'));
}
if(!App::user()->hasAccess('ext_name: manage all items')) {
$data['user_id'] = App::user()->id;
}
if(!App::user()->hasAccess('ext_name: manage all items') && !App::user()->hasAccess('ext_name: manage own items') && $item->user_id !== App::user()->id) {
App::abort(403, __('Access denied'));
}
$item->save($data);
/*
* Here I need to sync $item->types with $selected_types ids
*/
return [
'message' => 'success',
'entity' => $item,
];
}
如果我有当前的项目ID和新的类型ID,我如何同步这种关系?