I have the model with following relations:
$this->belongsTo('consolidator_id', 'Models\\Companies', 'id', array('alias' => 'Consolidators'));
$this->belongsTo('customer_id', 'Models\\Companies', 'id', array('alias' => 'Customers'));
Then I try to leftJoin() the related models:
$this->modelsManager->createBuilder()
->from(['Orders' => 'Models\Orders'])
->columns([
'Customers.name as customerName',
'Consolidators.name as consolidatorName',
])
->leftJoin('Models\Companies', null, 'Customers')
->leftJoin('Models\Companies', null, 'Consolidators');
But I get the error:
There is more than one relation between models 'Models\Orders' and 'Models\Companies', the join must be done using an alias, when preparing: SELECT Customers.name as customerName, Consolidators.name as consolidatorName FROM [Models\Orders] AS [Orders] LEFT JOIN [Models\Companies] AS [Customers] LEFT JOIN [Models\Companies] AS [Consolidators]
#0 [internal function]: Phalcon\Mvc\Model\Query->_getJoins(Array)
#1 [internal function]: Phalcon\Mvc\Model\Query->_prepareSelect()
#2 [internal function]: Phalcon\Mvc\Model\Query->parse()
When you try to use getRelationByAlias() method of Phalcon\Mvc\Model\Manager it always will return false, unless you initialize() your model first. This is not really intuitive behaviour. Going further you will always get empty array from getRelations() method.
$this->modelsManager->initialize(new Orders());
var_dump($this->modelsManager->getRelationByAlias(
'Models\\Orders',
'Consolidators'
));
I went to the Phalcon repository, and found the following code there (line 1517 - 1546):
/**
* Get the model name from its source
*/
let modelNameAlias = sqlAliasesModels[joinAlias];
/**
* Check if the joined model is an alias
*/
let relation = manager->getRelationByAlias(fromModelName, modelNameAlias);
if relation === false {
/**
* Check for relations between models
*/
let relations = manager->getRelationsBetween(fromModelName, modelNameAlias);
if typeof relations == "array" {
/**
* More than one relation must throw an exception
*/
if count(relations) != 1 {
throw new Exception("There is more than one relation between models '" . fromModelName . "' and '" . joinModel . "', the join must be done using an alias, when preparing: " . this->_phql);
}
/**
* Get the first relationship
*/
let relation = relations[0];
}
}
This is the place where exception is thrown from. I guess there is problem with this code - manager->getRelationsBetween(fromModelName, modelNameAlias); will always return false, unless the model is somehow initialized in the manager first. I concluded this from the example above.
Is this a bug, or am I missing something?