Completed
Push — master ( afd60e...0cfe13 )
by Philip
02:44
created

MySQLData::enrichWithMany()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 11
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 11
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 8
nc 4
nop 1
1
<?php
2
3
/*
4
 * This file is part of the CRUDlex package.
5
 *
6
 * (c) Philip Lehmann-Böhm <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace CRUDlex;
13
14
use Doctrine\DBAL\Query\QueryBuilder;
15
use Doctrine\DBAL\Connection;
16
17
/**
18
 * MySQL Data implementation using a given Doctrine DBAL instance.
19
 */
20
class MySQLData extends AbstractData {
21
22
    /**
23
     * Holds the Doctrine DBAL instance.
24
     */
25
    protected $database;
26
27
    /**
28
     * Flag whether to use UUIDs as primary key.
29
     */
30
    protected $useUUIDs;
31
32
    /**
33
     * Gets the many-to-many fields.
34
     *
35
     * @return array|\string[]
36
     * the many-to-many fields
37
     */
38
    protected function getManyFields() {
39
        $fields = $this->definition->getFieldNames(true);
40
        return array_filter($fields, function($field) {
41
            return $this->definition->getType($field) === 'many';
42
        });
43
    }
44
45
    /**
46
     * Gets all form fields including the many-to-many-ones.
47
     *
48
     * @return array
49
     * all form fields
50
     */
51
    protected function getFormFields() {
52
        $manyFields = $this->getManyFields();
53
        $formFields = [];
54
        foreach ($this->definition->getEditableFieldNames() as $field) {
55
            if (!in_array($field, $manyFields)) {
56
                $formFields[] = $field;
57
            }
58
        }
59
        return $formFields;
60
    }
61
62
    /**
63
     * Sets the values and parameters of the upcoming given query according
64
     * to the entity.
65
     *
66
     * @param Entity $entity
67
     * the entity with its fields and values
68
     * @param QueryBuilder $queryBuilder
69
     * the upcoming query
70
     * @param string $setMethod
71
     * what method to use on the QueryBuilder: 'setValue' or 'set'
72
     */
73
    protected function setValuesAndParameters(Entity $entity, QueryBuilder $queryBuilder, $setMethod) {
74
        $formFields = $this->getFormFields();
75
        $count      = count($formFields);
76
        for ($i = 0; $i < $count; ++$i) {
77
            $type  = $this->definition->getType($formFields[$i]);
78
            $value = $entity->get($formFields[$i]);
79
            if ($type == 'boolean') {
80
                $value = $value ? 1 : 0;
81
            }
82
            $queryBuilder->$setMethod('`'.$formFields[$i].'`', '?');
83
            $queryBuilder->setParameter($i, $value);
84
        }
85
    }
86
87
    /**
88
     * Performs the cascading children deletion.
89
     *
90
     * @param integer $id
91
     * the current entities id
92
     * @param boolean $deleteCascade
93
     * whether to delete children and sub children
94
     */
95
    protected function deleteChildren($id, $deleteCascade) {
96
        foreach ($this->definition->getChildren() as $childArray) {
97
            $childData = $this->definition->getServiceProvider()->getData($childArray[2]);
98
            $children  = $childData->listEntries([$childArray[1] => $id]);
99
            foreach ($children as $child) {
100
                $childData->doDelete($child, $deleteCascade);
101
            }
102
        }
103
    }
104
105
    /**
106
     * Checks whether the by id given entity still has children referencing it.
107
     *
108
     * @param integer $id
109
     * the current entities id
110
     *
111
     * @return boolean
112
     * true if the entity still has children
113
     */
114
    protected function hasChildren($id) {
115
        foreach ($this->definition->getChildren() as $child) {
116
            $queryBuilder = $this->database->createQueryBuilder();
117
            $queryBuilder
118
                ->select('COUNT(id)')
119
                ->from('`'.$child[0].'`', '`'.$child[0].'`')
120
                ->where('`'.$child[1].'` = ?')
121
                ->andWhere('deleted_at IS NULL')
122
                ->setParameter(0, $id);
123
            $queryResult = $queryBuilder->execute();
124
            $result      = $queryResult->fetch(\PDO::FETCH_NUM);
125
            if ($result[0] > 0) {
126
                return true;
127
            }
128
        }
129
        return false;
130
    }
131
132
    /**
133
     * {@inheritdoc}
134
     */
135
    protected function doDelete(Entity $entity, $deleteCascade) {
136
        $result = $this->shouldExecuteEvents($entity, 'before', 'delete');
137
        if (!$result) {
138
            return static::DELETION_FAILED_EVENT;
139
        }
140
        $id = $entity->get('id');
141
        if ($deleteCascade) {
142
            $this->deleteChildren($id, $deleteCascade);
143
        } elseif ($this->hasChildren($id)) {
144
            return static::DELETION_FAILED_STILL_REFERENCED;
145
        }
146
147
        $query = $this->database->createQueryBuilder();
148
        $query
149
            ->update('`'.$this->definition->getTable().'`')
150
            ->set('deleted_at', 'UTC_TIMESTAMP()')
151
            ->where('id = ?')
152
            ->setParameter(0, $id);
153
154
        $query->execute();
155
        $this->shouldExecuteEvents($entity, 'after', 'delete');
156
        return static::DELETION_SUCCESS;
157
    }
158
159
    /**
160
     * Gets all possible many-to-many ids existing for this definition.
161
     *
162
     * @param array $fields
163
     * the many field names to fetch for
164
     * @param $params
165
     * the parameters the possible many field values to fetch for
166
     * @return array
167
     * an array of this many-to-many ids
168
     */
169
    protected function getManyIds(array $fields, array $params) {
170
        $manyIds = [];
171
        foreach ($fields as $field) {
172
            $thisField    = $this->definition->getManyThisField($field);
173
            $thatField    = $this->definition->getManyThatField($field);
174
            $queryBuilder = $this->database->createQueryBuilder();
175
            $queryBuilder
176
                ->select('`'.$thisField.'`')
177
                ->from($field)
178
                ->where('`'.$thatField.'` IN (?)')
179
                ->setParameter(0, array_column($params[$field], 'id'), Connection::PARAM_STR_ARRAY)
180
                ->groupBy('`'.$thisField.'`')
181
            ;
182
            $queryResult = $queryBuilder->execute();
183
            $manyResults = $queryResult->fetchAll(\PDO::FETCH_ASSOC);
184
            foreach ($manyResults as $manyResult) {
185
                if (!in_array($manyResult[$thisField], $manyIds)) {
186
                    $manyIds[] = $manyResult[$thisField];
187
                }
188
            }
189
        }
190
        return $manyIds;
191
    }
192
193
    /**
194
     * Adds sorting parameters to the query.
195
     *
196
     * @param QueryBuilder $queryBuilder
197
     * the query
198
     * @param $filter
199
     * the filter all resulting entities must fulfill, the keys as field names
200
     * @param $filterOperators
201
     * the operators of the filter like "=" defining the full condition of the field
202
     */
203
    protected function addFilter(QueryBuilder $queryBuilder, array $filter, array $filterOperators) {
204
        $i          = 0;
205
        $manyFields = [];
206
        foreach ($filter as $field => $value) {
207
            if ($this->definition->getType($field) === 'many') {
208
                $manyFields[] = $field;
209
                continue;
210
            }
211
            if ($value === null) {
212
                $queryBuilder->andWhere('`'.$field.'` IS NULL');
213
            } else {
214
                $operator = array_key_exists($field, $filterOperators) ? $filterOperators[$field] : '=';
215
                $queryBuilder
216
                    ->andWhere('`'.$field.'` '.$operator.' ?')
217
                    ->setParameter($i, $value, \PDO::PARAM_STR);
218
            }
219
            $i++;
220
        }
221
        $idsToInclude = $this->getManyIds($manyFields, $filter);
222
        if (!empty($idsToInclude)) {
223
            $queryBuilder
224
                ->andWhere('id IN (?)')
225
                ->setParameter($i, $idsToInclude, Connection::PARAM_STR_ARRAY)
226
            ;
227
        }
228
    }
229
230
    /**
231
     * Adds pagination parameters to the query.
232
     *
233
     * @param QueryBuilder $queryBuilder
234
     * the query
235
     * @param integer|null $skip
236
     * the rows to skip
237
     * @param integer|null $amount
238
     * the maximum amount of rows
239
     */
240
    protected function addPagination(QueryBuilder $queryBuilder, $skip, $amount) {
241
        $queryBuilder->setMaxResults(9999999999);
242
        if ($amount !== null) {
243
            $queryBuilder->setMaxResults(abs(intval($amount)));
244
        }
245
        if ($skip !== null) {
246
            $queryBuilder->setFirstResult(abs(intval($skip)));
247
        }
248
    }
249
250
    /**
251
     * Adds sorting parameters to the query.
252
     *
253
     * @param QueryBuilder $queryBuilder
254
     * the query
255
     * @param string|null $sortField
256
     * the sort field
257
     * @param boolean|null $sortAscending
258
     * true if sort ascending, false if descending
259
     */
260
    protected function addSort(QueryBuilder $queryBuilder, $sortField, $sortAscending) {
261
        if ($sortField !== null) {
262
263
            $type = $this->definition->getType($sortField);
264
            if ($type === 'many') {
265
                $sortField = $this->definition->getInitialSortField();
266
            }
267
268
            $order = $sortAscending === true ? 'ASC' : 'DESC';
269
            $queryBuilder->orderBy('`'.$sortField.'`', $order);
270
        }
271
    }
272
273
    /**
274
     * Adds the id and name of referenced entities to the given entities. The
275
     * reference field is before the raw id of the referenced entity and after
276
     * the fetch, it's an array with the keys id and name.
277
     *
278
     * @param Entity[] &$entities
279
     * the entities to fetch the references for
280
     * @param string $field
281
     * the reference field
282
     */
283
    protected function fetchReferencesForField(array &$entities, $field) {
284
        $nameField    = $this->definition->getReferenceNameField($field);
285
        $queryBuilder = $this->database->createQueryBuilder();
286
287
        $ids = array_map(function(Entity $entity) use ($field) {
288
            return $entity->get($field);
289
        }, $entities);
290
291
        $referenceEntity = $this->definition->getReferenceEntity($field);
292
        $table           = $this->definition->getServiceProvider()->getData($referenceEntity)->getDefinition()->getTable();
293
        $queryBuilder
294
            ->from('`'.$table.'`', '`'.$table.'`')
295
            ->where('id IN (?)')
296
            ->andWhere('deleted_at IS NULL');
297
        if ($nameField) {
298
            $queryBuilder->select('id', $nameField);
299
        } else {
300
            $queryBuilder->select('id');
301
        }
302
303
        $queryBuilder->setParameter(0, $ids, Connection::PARAM_STR_ARRAY);
304
305
        $queryResult = $queryBuilder->execute();
306
        $rows        = $queryResult->fetchAll(\PDO::FETCH_ASSOC);
307
        $amount      = count($entities);
308
        foreach ($rows as $row) {
309
            for ($i = 0; $i < $amount; ++$i) {
310
                if ($entities[$i]->get($field) == $row['id']) {
311
                    $value = ['id' => $entities[$i]->get($field)];
312
                    if ($nameField) {
313
                        $value['name'] = $row[$nameField];
314
                    }
315
                    $entities[$i]->set($field, $value);
316
                }
317
            }
318
        }
319
    }
320
321
    /**
322
     * Generates a new UUID.
323
     *
324
     * @return string|null
325
     * the new UUID or null if this instance isn't configured to do so
326
     */
327
    protected function generateUUID() {
328
        $uuid = null;
329
        if ($this->useUUIDs) {
330
            $sql    = 'SELECT UUID() as id';
331
            $result = $this->database->fetchAssoc($sql);
332
            $uuid   = $result['id'];
333
        }
334
        return $uuid;
335
    }
336
337
    /**
338
     * Enriches the given mapping of entity id to raw entity data with some many-to-many data.
339
     *
340
     * @param array $idToData
341
     * a reference to the map entity id to raw entity data
342
     * @param $manyField
343
     * the many field to enrich data with
344
     */
345
    protected function enrichWithManyField(&$idToData, $manyField) {
346
        $queryBuilder = $this->database->createQueryBuilder();
347
        $nameField    = $this->definition->getManyNameField($manyField);
348
        $thisField    = $this->definition->getManyThisField($manyField);
349
        $thatField    = $this->definition->getManyThatField($manyField);
350
        $entity       = $this->definition->getManyEntity($manyField);
351
        $entityTable  = $this->definition->getServiceProvider()->getData($entity)->getDefinition()->getTable();
352
        $nameSelect   = $nameField !== null ? ', t2.`'.$nameField.'` AS name' : '';
353
        $queryBuilder
354
            ->select('t1.`'.$thisField.'` AS this, t1.`'.$thatField.'` AS id'.$nameSelect)
355
            ->from('`'.$manyField.'`', 't1')
356
            ->leftJoin('t1', '`'.$entityTable.'`', 't2', 't2.id = t1.`'.$thatField.'`')
357
            ->where('t1.`'.$thisField.'` IN (?)')
358
            ->andWhere('t2.deleted_at IS NULL');
359
        $queryBuilder->setParameter(0, array_keys($idToData), Connection::PARAM_STR_ARRAY);
360
        $queryResult    = $queryBuilder->execute();
361
        $manyReferences = $queryResult->fetchAll(\PDO::FETCH_ASSOC);
362
        foreach ($manyReferences as $manyReference) {
363
            $entityId = $manyReference['this'];
364
            unset($manyReference['this']);
365
            $idToData[$entityId][$manyField][] = $manyReference;
366
        }
367
    }
368
369
    /**
370
     * Fetches to the rows belonging many-to-many entries and adds them to the rows.
371
     *
372
     * @param array $rows
373
     * the rows to enrich
374
     * @return array
375
     * the enriched rows
376
     */
377
    protected function enrichWithMany(array $rows) {
378
        $manyFields = $this->getManyFields();
379
        $idToData    = [];
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 3 spaces but found 4 spaces

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
380
        foreach ($rows as $row) {
381
            $idToData[$row['id']] = $row;
382
        }
383
        foreach ($manyFields as $manyField) {
384
            $this->enrichWithManyField($idToData, $manyField);
385
        }
386
        return array_values($idToData);
387
    }
388
389
    /**
390
     * First, deletes all to the given entity related many-to-many entries from the DB
391
     * and then writes them again.
392
     *
393
     * @param Entity $entity
394
     * the entity to save the many-to-many entries of
395
     */
396
    protected function saveMany(Entity $entity) {
397
        $manyFields = $this->getManyFields();
398
        $id = $entity->get('id');
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 9 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
399
        foreach ($manyFields as $manyField) {
400
            $thisField = $this->definition->getManyThisField($manyField);
401
            $thatField = $this->definition->getManyThatField($manyField);
402
            $this->database->delete($manyField, [$thisField => $id]);
403
            foreach ($entity->get($manyField) as $thatId) {
404
                $this->database->insert($manyField, [
405
                    $thisField => $id,
406
                    $thatField => $thatId['id']
407
                ]);
408
            }
409
        }
410
    }
411
412
    /**
413
     * Constructor.
414
     *
415
     * @param EntityDefinition $definition
416
     * the entity definition
417
     * @param FileProcessorInterface $fileProcessor
418
     * the file processor to use
419
     * @param $database
420
     * the Doctrine DBAL instance to use
421
     * @param boolean $useUUIDs
422
     * flag whether to use UUIDs as primary key
423
     */
424
    public function __construct(EntityDefinition $definition, FileProcessorInterface $fileProcessor, $database, $useUUIDs) {
425
        $this->definition    = $definition;
426
        $this->fileProcessor = $fileProcessor;
427
        $this->database      = $database;
428
        $this->useUUIDs      = $useUUIDs;
429
    }
430
431
    /**
432
     * {@inheritdoc}
433
     */
434
    public function get($id) {
435
        $entities = $this->listEntries(['id' => $id]);
436
        if (count($entities) == 0) {
437
            return null;
438
        }
439
        return $entities[0];
440
    }
441
442
    /**
443
     * {@inheritdoc}
444
     */
445
    public function listEntries(array $filter = [], array $filterOperators = [], $skip = null, $amount = null, $sortField = null, $sortAscending = null) {
446
        $fieldNames = $this->definition->getFieldNames();
447
448
        $queryBuilder = $this->database->createQueryBuilder();
449
        $table        = $this->definition->getTable();
450
        $queryBuilder
451
            ->select('`'.implode('`,`', $fieldNames).'`')
452
            ->from('`'.$table.'`', '`'.$table.'`')
453
            ->where('deleted_at IS NULL');
454
455
        $this->addFilter($queryBuilder, $filter, $filterOperators);
456
        $this->addPagination($queryBuilder, $skip, $amount);
457
        $this->addSort($queryBuilder, $sortField, $sortAscending);
458
459
        $queryResult = $queryBuilder->execute();
460
        $rows        = $queryResult->fetchAll(\PDO::FETCH_ASSOC);
461
        $rows        = $this->enrichWithMany($rows);
462
        $entities    = [];
463
        foreach ($rows as $row) {
464
            $entities[] = $this->hydrate($row);
465
        }
466
        return $entities;
467
    }
468
469
    /**
470
     * {@inheritdoc}
471
     */
472
    public function create(Entity $entity) {
473
474
        $result = $this->shouldExecuteEvents($entity, 'before', 'create');
475
        if (!$result) {
476
            return false;
477
        }
478
479
        $queryBuilder = $this->database->createQueryBuilder();
480
        $queryBuilder
481
            ->insert('`'.$this->definition->getTable().'`')
482
            ->setValue('created_at', 'UTC_TIMESTAMP()')
483
            ->setValue('updated_at', 'UTC_TIMESTAMP()')
484
            ->setValue('version', 0);
485
486
487
        $this->setValuesAndParameters($entity, $queryBuilder, 'setValue');
488
489
        $id = $this->generateUUID();
490
        if ($this->useUUIDs) {
491
            $queryBuilder->setValue('`id`', '?');
492
            $uuidI = count($this->getFormFields());
493
            $queryBuilder->setParameter($uuidI, $id);
494
        }
495
496
        $queryBuilder->execute();
497
498
        if (!$this->useUUIDs) {
499
            $id = $this->database->lastInsertId();
500
        }
501
502
        $entity->set('id', $id);
503
504
        $createdEntity = $this->get($entity->get('id'));
505
        $entity->set('version', $createdEntity->get('version'));
506
        $entity->set('created_at', $createdEntity->get('created_at'));
507
        $entity->set('updated_at', $createdEntity->get('updated_at'));
508
509
        $this->saveMany($entity);
510
511
        $this->shouldExecuteEvents($entity, 'after', 'create');
512
513
        return true;
514
    }
515
516
    /**
517
     * {@inheritdoc}
518
     */
519
    public function update(Entity $entity) {
520
521
        $result = $this->shouldExecuteEvents($entity, 'before', 'update');
522
        if (!$result) {
523
            return false;
524
        }
525
526
        $formFields   = $this->getFormFields();
527
        $queryBuilder = $this->database->createQueryBuilder();
528
        $queryBuilder
529
            ->update('`'.$this->definition->getTable().'`')
530
            ->set('updated_at', 'UTC_TIMESTAMP()')
531
            ->set('version', 'version + 1')
532
            ->where('id = ?')
533
            ->setParameter(count($formFields), $entity->get('id'));
534
535
        $this->setValuesAndParameters($entity, $queryBuilder, 'set');
536
        $affected = $queryBuilder->execute();
537
538
        $this->saveMany($entity);
539
540
        $this->shouldExecuteEvents($entity, 'after', 'update');
541
542
        return $affected;
543
    }
544
545
    /**
546
     * {@inheritdoc}
547
     */
548
    public function getIdToNameMap($entity, $nameField) {
549
        $table = $this->definition->getServiceProvider()->getData($entity)->getDefinition()->getTable();
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 8 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
550
        $queryBuilder = $this->database->createQueryBuilder();
551
        $nameSelect   = $nameField !== null ? ',`'.$nameField.'`' : '';
552
        $queryBuilder
553
            ->select('id'.$nameSelect)
554
            ->from('`'.$table.'`', 't1')
555
            ->where('deleted_at IS NULL');
556
        if ($nameField) {
557
            $queryBuilder->orderBy($nameField);
558
        } else {
559
            $queryBuilder->orderBy('id');
560
        }
561
        $queryResult    = $queryBuilder->execute();
562
        $manyReferences = $queryResult->fetchAll(\PDO::FETCH_ASSOC);
563
        $result         = [];
564
        foreach ($manyReferences as $manyReference) {
565
            $result[$manyReference['id']] = $nameField ? $manyReference[$nameField] : $manyReference['id'];
566
        }
567
        return $result;
568
    }
569
570
    /**
571
     * {@inheritdoc}
572
     */
573
    public function countBy($table, array $params, array $paramsOperators, $excludeDeleted) {
574
        $queryBuilder = $this->database->createQueryBuilder();
575
        $queryBuilder
576
            ->select('COUNT(id)')
577
            ->from('`'.$table.'`', '`'.$table.'`')
578
        ;
579
580
        $deletedExcluder = 'where';
581
        $i               = 0;
582
        $manyFields      = [];
583
        foreach ($params as $name => $value) {
584
            if ($this->definition->getType($name) === 'many') {
585
                $manyFields[] = $name;
586
                continue;
587
            }
588
            $queryBuilder
589
                ->andWhere('`'.$name.'` '.$paramsOperators[$name].' ?')
590
                ->setParameter($i, $value, \PDO::PARAM_STR)
591
            ;
592
            $i++;
593
            $deletedExcluder = 'andWhere';
594
        }
595
596
        $idsToInclude = $this->getManyIds($manyFields, $params);
597
        if (!empty($idsToInclude)) {
598
            $queryBuilder
599
                ->andWhere('id IN (?)')
600
                ->setParameter($i, $idsToInclude, Connection::PARAM_STR_ARRAY)
601
            ;
602
            $deletedExcluder = 'andWhere';
603
        }
604
605
        if ($excludeDeleted) {
606
            $queryBuilder->$deletedExcluder('deleted_at IS NULL');
607
        }
608
609
        $queryResult = $queryBuilder->execute();
610
        $result      = $queryResult->fetch(\PDO::FETCH_NUM);
611
        return intval($result[0]);
612
    }
613
614
    /**
615
     * {@inheritdoc}
616
     */
617
    public function fetchReferences(array &$entities = null) {
618
        if (!$entities) {
619
            return;
620
        }
621
        foreach ($this->definition->getFieldNames() as $field) {
622
            if ($this->definition->getType($field) !== 'reference') {
623
                continue;
624
            }
625
            $this->fetchReferencesForField($entities, $field);
626
        }
627
    }
628
629
630
    /**
631
     * {@inheritdoc}
632
     */
633
    public function hasManySet($field, array $thatIds) {
634
        $thisField    = $this->definition->getManyThisField($field);
635
        $thatField    = $this->definition->getManyThatField($field);
636
        $thatEntity   = $this->definition->getManyEntity($field);
637
        $entityTable  = $this->definition->getServiceProvider()->getData($thatEntity)->getDefinition()->getTable();
638
        $queryBuilder = $this->database->createQueryBuilder();
639
        $queryBuilder
640
            ->select('t1.`'.$thisField.'` AS this, t1.`'.$thatField.'` AS that')
641
            ->from('`'.$field.'`', 't1')
642
            ->leftJoin('t1', '`'.$entityTable.'`', 't2', 't2.id = t1.`'.$thatField.'`')
643
            ->andWhere('t2.deleted_at IS NULL')
644
            ->orderBy('this, that');
645
        $queryResult  = $queryBuilder->execute();
646
        $existingMany = $queryResult->fetchAll(\PDO::FETCH_ASSOC);
647
        $existingMap  = [];
648
        foreach ($existingMany as $existing) {
649
            $existingMap[$existing['this']][] = $existing['that'];
650
        }
651
        sort($thatIds);
652
        return in_array($thatIds, array_values($existingMap));
653
    }
654
655
}
656