protected function _collectJointEntities($sourceEntity, $targetEntities)
{
$target = $this->target();
$source = $this->source();
$junction = $this->junction();
$jointProperty = $this->_junctionProperty;
$primary = (array) $target->primaryKey();
$result = [];
$missing = [];
foreach ($targetEntities as $entity) {
if (!$entity instanceof EntityInterface) {
continue;
}
$joint = $entity->get($jointProperty);
if (!$joint || !$joint instanceof EntityInterface) {
$missing[] = $entity->extract($primary);
continue;
}
$result[] = $joint;
}
if (empty($missing)) {
return $result;
}
$belongsTo = $junction->association($target->alias());
$hasMany = $source->association($junction->alias());
$foreignKey = (array) $this->foreignKey();
$assocForeignKey = (array) $belongsTo->foreignKey();
$sourceKey = $sourceEntity->extract((array) $source->primaryKey());
foreach ($missing as $key) {
$unions[] = $hasMany->find('all')->where(array_combine($foreignKey, $sourceKey))->andWhere(array_combine($assocForeignKey, $key));
}
$query = array_shift($unions);
foreach ($unions as $q) {
$query->union($q);
}
return array_merge($result, $query->toArray());
}