Views: 3058
Last Modified: 24.08.2023
Detailed description can be found in the next article for Relations. However, you can find specifications for managing method relations below.
Relations fields can be handled by the already described methods get, require, fill, reset, unset.
Important! Despite the fact that Collections object is used as a relations value, relations can be modified only via the methods
addTo,
removeFrom,
removeAll for partner objects. Modifying a collection directly (
add,
remove) doesn't lead to a desirable result.
- addTo
The addTo method adds a new relations between objects:
// publisher initialization
$publisher = \Bitrix\Main\Test\Typography\PublisherTable::getByPrimary(253)
->fetchObject();
// book initialization
$book = \Bitrix\Main\Test\Typography\BookTable::getByPrimary(2)
->fetchObject();
// adding book to a relation collection
$publisher->addToBooks($book);
// saving
$publisher->save();
Calling the method binds the object only in the system memory, you need to register the changes using the save method.
- removeFrom
Deleting relation associations - removeFrom - operates in a similar manner:
// publisher initialization
$publisher = \Bitrix\Main\Test\Typography\PublisherTable::getByPrimary(253)
->fetchObject();
// book initialization
$book = \Bitrix\Main\Test\Typography\BookTable::getByPrimary(2)
->fetchObject();
// deleting a single specific publisher book
$publisher->removeFromBooks($book);
// saving
$publisher->save();
- removeAll
Deleting all records can be done via a single call:
// publisher initialization
$publisher = \Bitrix\Main\Test\Typography\PublisherTable::getByPrimary(253)
->fetchObject();
// deleting all publisher books
$publisher->removeAllBooks();
// saving
$publisher->save();
This operation requires knowledge of the source value: which Books are available at the Publisher presently. That's why, if BOOKS field is not initially accessed, it will be accessed automatically before deleting.
As an alternative, you can use generic unnamed methods:
$fieldName = 'BOOKS';
$publisher->addTo($fieldName, $book);
$publisher->removeFrom($fieldName, $book);
$publisher->removeAll($fieldName);