Answer the question
In order to leave comments, you need to log in
Bitrix D7 ORM: how to find out the ID of an existing record?
Created the BookTable entity . Added UniqueValidator for NAME field . Now, if a duplicate is found, the record is not added, and Result::isSuccess returns false .
class BookTable extends DataManager
{
public static function getMap()
{
return [
new Fields\IntegerField('ID', [
'primary' => true,
'autocomplete' => true,
]),
new Fields\TextField('NAME', [
'validation' => function() {
return [
new Fields\Validators\UniqueValidator('Not unique'),
];
}
]),
];
}
}
$result = BookTable::add([
'NAME' => 'NAME',
]);
if ($result->isSuccess()) {
$result->getId();
} else {
BookTable::getRow(['select' => ['ID'], 'filter' => ['NAME' => 'NAME']])['ID']; // Приходится делать дополнительный запрос
}
Answer the question
In order to leave comments, you need to log in
Yes, OK.
But I add that such a solution as suggested by eugenezadorin will only be good in a situation where duplicates are a very likely and frequent occurrence. Otherwise, the best solution would be to collect in a separate array in the cycle the names that were rejected due to duplication, and therefore, at the end of the adding cycle, if the cycle of names is not empty, get the id list corresponding to the names collected in the request with one request.
The advantage is that if there are no conflicts, the request is not made at all.
By the way, if the addition is not in a cycle, and your probability of duplicates is more than 50% (even possibly 40%), then the best solution would be to first check if there is already an entry with the same name and only therefore perform the addition if it does not exist.
Adequate if it's a single add operation - for example, if it's a form submission.
Performance can be degraded if such an addition occurs in a loop, and there will be many duplicate names. In this case, it might be better to form a directory of existing books "name - id" in advance, and check it before adding it.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question