public function getQuery()
{
if (null !== $this->query) {
return $this->query;
}
$provider = $this->createProvider($this->getEntity());
$foreignProvider = $this->createProvider($this->getForeignEntity());
$foreignKey = $this->getForeignKey();
$junction = $this->getJunction();
$junctionLocalKey = $this->getJunctionLocalKey();
$junctionForeignKey = $this->getJunctionForeignKey();
$data = $provider->extract();
$localKey = $provider->getDefinition()->getPrimaryKeyName();
//determine foreign key
if ($foreignKey === null) {
$foreignKey = $foreignProvider->getDefinition()->getPrimaryKeyName();
}
//determine through
if (!is_string($junction) || $junction === null) {
$junction = Inflector::singularize($provider->getDefinition()->getTableName()) . '_' . Inflector::singularize($foreignProvider->getDefinition()->getTableName());
}
//determine through local key
if ($junctionLocalKey === null) {
$junctionLocalKey = Inflector::singularize($provider->getDefinition()->getTableName()) . '_' . $localKey;
}
//determine through foreign key
if ($junctionForeignKey === null) {
$junctionForeignKey = Inflector::singularize($foreignProvider->getDefinition()->getTableName()) . '_' . $foreignKey;
}
$query = new Query($provider->getDefinition()->getMapper()->getConnection());
//prepare query for foreign table
$foreignQuery = $foreignProvider->getDefinition()->getMapper()->setConnection($this->getConnection())->select();
//get relations by through db object
if (isset($data[$localKey])) {
$junctionProvider = is_string($junction) ? $this->createProvider($junction) : $junction;
$junctionMapper = $junctionProvider->getDefinition()->getMapper();
$junctionMapper->setConnection($this->getConnection());
if (true) {
}
$results = $junctionMapper->select([$junctionForeignKey])->where($query->expr()->eq($junctionLocalKey, $data[$localKey]))->execute(HydratorInterface::HYDRATE_RAW);
//set conditions on foreign query
foreach ($results as $result) {
$foreignQuery->where($query->expr()->eq($foreignKey, $result[$junctionForeignKey]));
}
}
$this->query = $foreignQuery;
return $this->query;
}