public function getQuery()
{
if (null !== $this->query) {
return $this->query;
}
$provider = $this->createProvider($this->getEntity());
$foreignProvider = $this->createProvider($this->getForeignEntity());
$localKey = $this->getLocalKey();
if ($localKey === null) {
$localKey = Inflector::singularize($foreignProvider->getDefinition()->getTableName()) . '_' . $foreignProvider->getDefinition()->getPrimaryKeyName();
}
$data = $provider->extract();
//find primary key
$primaryKey = $data[$localKey];
$mapper = $foreignProvider->getDefinition()->getMapper()->setConnection($this->getConnection());
//if no primary key is available, return a select
$this->query = $primaryKey === null ? $mapper->select() : $mapper->find($primaryKey);
return $this->query;
}