CRUDlex\MySQLData::fetchReferencesForField PHP Method

fetchReferencesForField() protected method

Adds the id and name of referenced entities to the given entities. The reference field is before the raw id of the referenced entity and after the fetch, it's an array with the keys id and name.
protected fetchReferencesForField ( array &$entities, string $field )
$entities array
$field string the reference field
    protected function fetchReferencesForField(array &$entities, $field)
    {
        $nameField = $this->definition->getSubTypeField($field, 'reference', 'nameField');
        $queryBuilder = $this->database->createQueryBuilder();
        $ids = array_map(function (Entity $entity) use($field) {
            return $entity->get($field);
        }, $entities);
        $referenceEntity = $this->definition->getSubTypeField($field, 'reference', 'entity');
        $table = $this->definition->getServiceProvider()->getData($referenceEntity)->getDefinition()->getTable();
        $queryBuilder->from('`' . $table . '`', '`' . $table . '`')->where('id IN (?)')->andWhere('deleted_at IS NULL');
        if ($nameField) {
            $queryBuilder->select('id', $nameField);
        } else {
            $queryBuilder->select('id');
        }
        $queryBuilder->setParameter(0, $ids, Connection::PARAM_STR_ARRAY);
        $queryResult = $queryBuilder->execute();
        $rows = $queryResult->fetchAll(\PDO::FETCH_ASSOC);
        $amount = count($entities);
        foreach ($rows as $row) {
            for ($i = 0; $i < $amount; ++$i) {
                if ($entities[$i]->get($field) == $row['id']) {
                    $value = ['id' => $entities[$i]->get($field)];
                    if ($nameField) {
                        $value['name'] = $row[$nameField];
                    }
                    $entities[$i]->set($field, $value);
                }
            }
        }
    }