I'm working with PageKit CMS. I have 2 tables with Many To Many relation (item and type).
Item model:
class Item implements \JsonSerializable
{
...
/**
* @ManyToMany(targetEntity="Type", tableThrough="@prefix_item_type", keyThroughFrom="item_id", keyThroughTo="type_id")
*/
public $types;
...
}
Type model:
class Type implements \JsonSerializable
{
...
/**
* @ManyToMany(targetEntity="Item", tableThrough="@prefix_item_type", keyThroughFrom="type_id", keyThroughTo="item_id")
*/
public $items;
...
}
In backend interface on item edit page I created multi select with all types. When I send item save request, I get type ids.
My save item method have a look:
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,
];
}
How can I sync this relation if I have current item id and new type ids?