Cake\ORM\Association\BelongsToMany::_collectJointEntities PHP Method

_collectJointEntities() protected method

Returns the list of joint entities that exist between the source entity and each of the passed target entities
protected _collectJointEntities ( Cake\Datasource\EntityInterface $sourceEntity, array $targetEntities ) : array
$sourceEntity Cake\Datasource\EntityInterface The row belonging to the source side of this association.
$targetEntities array The rows belonging to the target side of this association.
return array
    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());
    }