R
R
ragnar_ok2019-09-28 22:17:44
1C-Bitrix
ragnar_ok, 2019-09-28 22:17:44

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'),
                    ];
                }
            ]),
        ];
    }
}

How to get the ID of an already existing record with this NAME in case of a duplicate detection ?
Right now I'm using BookTable::getRow filtered by NAME in case there is a duplicate.
$result = BookTable::add([
    'NAME' => 'NAME',
]);

if ($result->isSuccess()) {
    $result->getId();
} else {
    BookTable::getRow(['select' => ['ID'], 'filter' => ['NAME' => 'NAME']])['ID']; //  Приходится делать дополнительный запрос
}

Is this solution appropriate?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander, 2019-09-29
@ragnar_ok

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.

E
eugenezadorin, 2019-09-29
@eugenezadorin

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 question

Ask a Question

731 491 924 answers to any question