B
B
BonBon Slick2021-08-29 02:02:27
SQL
BonBon Slick, 2021-08-29 02:02:27

How to check if it is possible to join on a table before the join in DQL?

/**
     * @throws JoinIsNotSupportedException
     * @throws ReflectionException
     */
    protected function innerJoinTablesIfNotJoined(
        QueryBuilder $query,
        string $joinToTableName,
        array $checkTablesNamesAliases
    ): QueryBuilder {
        $joinedAliases             = $query->getAllAliases();
        $firstSelectFromTableClass = $query->getRootEntities()[0];
        $paramList                 = $this->getObjectPropertiesNames($firstSelectFromTableClass);
        foreach ($checkTablesNamesAliases as $joinTableAlias) {
            if (false === in_array($joinTableAlias, $paramList, true)) {
                throw  JoinIsNotSupportedException::joinNotSupported($joinToTableName, $joinTableAlias, $paramList);
            }
            if (false === \in_array($joinTableAlias, $joinedAliases, true)) {
                $query->join(\sprintf('%s.%s', $joinToTableName, $joinTableAlias), $joinTableAlias);
            }
        }

        return $query;
    }


The problem is that it $query->getRootEntities()[0];will return only the root entity, the main table from which the selection is made and to which the joins. If we have the 2nd join, for example
Make a selection from table posts -> join -> user -> join -> comments

posts -> join -> userwill work correctly firstSelectFromTableClass === 'posts'
But any level 2+ joy and deeper will already fall.
Maybe you can somehow get the metadata of the fields and their metadata, or check whether there is such a field on pure SQL.

The check is necessary to avoid table joins that don't exist.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question