@function buildWhereRelationDirect

build where clause for related model that is reference directly

@param {string} name
@param {array|boolean|object|string} value
@param {object} relation

@throws {Error}
484465
function buildWhereRelationDirect (name, value, relation) {
    // create alias for relation table to use in query
    var relationAlias = this.newAlias(relation.model.name)
    // get param name
    var paramName = this.newParam(relation.modelIdColumn)
    // get placeholder
    var placeholder = this.unhexId(`:${paramName}`)
    // build sql
    var whereSql = `${this.alias}.${this.quoteName(relation.modelIdColumn)} = ${placeholder}`
    // add value to params
    this.params[paramName] = value[relation.modelIdColumn]
    // add where clause to query
    this.where.push(whereSql)
}
967865
public function setRelated($name, $values)
    {
        $relation = $this->owner->getRelation($name, false);
        if ($relation === null) {
            return false;
        }
        $class = $relation->modelClass;
        $multiple = $relation->multiple;
        $link = $relation->link;
        $uniqueKeys = array_flip($class::primaryKey());
        foreach (array_keys($link) as $from) {
            unset($uniqueKeys[$from]);
        }
        $uniqueKeys = array_keys($uniqueKeys);
        if (isset($this->_original_relations[$name])) {
            $children = $this->_original_relations[$name];
        } else {
            $this->_original_relations[$name] = $children = $this->owner->$name;
        }

        if ($multiple) {
            $newChildren = [];
            foreach ($values as $index => $value) {
                // get from current relation
                // if has child with same primary key, use this
                /* @var $newChild \yii\db\ActiveRecord */
                $newChild = null;
                if (empty($relation->indexBy)) {
                    foreach ($children as $i => $child) {
                        if ($this->isEqual($child, $value, $uniqueKeys)) {
                            if ($value instanceof $class) {
                                $newChild = $value;
                                $newChild->isNewRecord = $child->isNewRecord;
                                $newChild->oldAttributes = $child->oldAttributes;
                            } else {
                                $newChild = $child;
                            }
                            unset($children[$i]);
                            break;
                        }
                    }
                } elseif (isset($children[$index])) {
                    $child = $children[$index];
                    if ($value instanceof $class) {
                        $newChild = $value;
                        $newChild->isNewRecord = $child->isNewRecord;
                        $newChild->oldAttributes = $child->oldAttributes;
                    } else {
                        $newChild = $child;
                    }
                    unset($children[$index]);
                }
                if ($newChild === null) {
                    $newChild = $value instanceof $class ? $value : new $class;
                }
                if (isset($this->relatedScenarios[$name])) {
                    $newChild->scenario = $this->relatedScenarios[$name];
                }
                if (!$value instanceof $class) {
                    $newChild->load($value, '');
                }
                foreach ($link as $from => $to) {
                    $newChild->$from = $this->owner->$to;
                }
                $newChildren[$index] = $newChild;
            }
            $this->_old_relations[$name] = $children;
            $this->owner->populateRelation($name, $newChildren);
            $this->_process_relation[$name] = true;
        } else {
            $newChild = null;
            if ($children === null) {
                if ($values !== null) {
                    $newChild = $values instanceof $class ? $values : new $class;
                    $this->_process_relation[$name] = true;
                }
            } else {
                if ($values !== null) {
                    $newChild = $values instanceof $class ? $values : $children;
                    if ($values instanceof $class) {
                        $newChild = $values;
                        $newChild->oldAttributes = $children->oldAttributes;
                        $newChild->isNewRecord = $children->isNewRecord;
                    } else {
                        $newChild = $children;
                    }
                } else {
                    $this->_old_relations[$name] = [$children];
                }
                $this->_process_relation[$name] = true;
            }
            if ($newChild !== null) {
                if (isset($this->relatedScenarios[$name])) {
                    $newChild->scenario = $this->relatedScenarios[$name];
                }
                if (!$values instanceof $class) {
                    $newChild->load($values, '');
                }
                foreach ($link as $from => $to) {
                    $newChild->$from = $this->owner->$to;
                }
            }
            $this->owner->populateRelation($name, $newChild);
        }
        return true;
    }
761040
public static function where($column, $relation, $value)
    {
        $self = self::instance();
        $key = $self->_keyName;
        $data = \Query::from($self->_table)->select($key)->where($column, $relation, $value)->get();
        $rows = [];

        if (!is_null($data)) {
            foreach ($data as $item) {
                $rows[] = self::instance($item->$key);
            }
        }

        return $rows;
    }
112668
public function orWhere($column, $relation, $value, $link = false)
    {
        if (!$link) {
            $this->where .= " or ( $column $relation '$value' )";
        } else {
            $this->where .= " or ( $column $relation $value )";
        }

        //
        return $this;
    }
1308515
function buildWhereRelationVia (name, value, relation) {
    // get relation model
    var relationModel = relation.model
    // create alias for relation table to use in query
    var relationAlias = this.newAlias(relationModel.name)
    // get via model
    var viaModel = relation.viaModel
    // create alias for via table to use in query
    var viaAlias = this.newAlias(viaModel.name)
    // join model table to via table
    this.join.push( this.joinSql(viaModel.name, viaAlias, relation.viaModelIdColumn, this.alias, relation.modelIdColumn) )
    // get param name
    var paramName = this.newParam(relation.viaRelationIdColumn)
    // get placeholder
    var placeholder = this.unhexId(`:${paramName}`)
    // build sql
    var whereSql = `${viaAlias}.${this.quoteName(relation.viaRelationIdColumn)} = ${placeholder}`
    // add value to params
    this.params[paramName] = value[relation.viaRelationIdColumn]
    // add where clause to query
    this.where.push(whereSql)
    // if via model does not support delete then skip
    if (!defined(viaModel.columns.d)) {
        return
    }
    // get id column names for via table
    var viaIdColumn = viaModel.defaultColumnsInverse.id
    var viaParentIdColumn = viaModel.defaultColumnsInverse.parentId
    // create new alias for joining revisions
    var viaRevisionAlias = this.newAlias(viaModel.name)
    // join viaModel on self to get current revision
    this.join.push( this.leftJoinSql(viaModel.name, viaRevisionAlias, viaParentIdColumn, viaAlias, viaIdColumn) )
    // add where clause to skip old revisions
    this.where.push(`${viaRevisionAlias}.${this.quoteName(viaIdColumn)} IS NULL`)
    // add where clause to skip deleted records
    this.where.push(`${viaAlias}.d = 0`)
}
535596
function _buildDependencies(links) {
  var deplist = [];
  // link would be 
  // link1: { parent:[], child:[] }
  _.each(links, function(link) {
    // get the value object that contains parent, child
    var l=_.values(link)[0];
    _.each(l.parent, function(p) {
      _.each(l.child, function(c) {
        deplist.push([c,p]);
      });
    });
  });
  return deplist;
}
995274
private void onRelationalAttributes(List<RelationHolder> rlHolders, Row row, Table schemaTable)
    {
        // Iterate over relations
        if (rlHolders != null && !rlHolders.isEmpty())
        {
            for (RelationHolder rh : rlHolders)
            {
                String relationName = rh.getRelationName();
                Object valueObj = rh.getRelationValue();

                if (!StringUtils.isEmpty(relationName) && valueObj != null)
                {
                    if (valueObj != null)
                    {
                        NoSqlDBUtils.add(schemaTable.getField(relationName), row, valueObj, relationName);
                        KunderaCoreUtils.printQuery(
                                "Add relation: relation name:" + relationName + "relation value:" + valueObj,
                                showQuery);
                    }
                }
            }
        }
    }
392735
public function add($field, $relation, $value)
	{
		$this->conditions[] = array(
				self::FIELD_POS => $field,
				self::RELATION_POS => $relation,
				self::VALUE_POS => $value
		);
	}
1084922
protected function setSingleRelation($relationName, $value)
    {
        /** @var BaseActiveRecord $owner */
        $owner = $this->owner;
        /** @var ActiveQuery $relation */
        $relation = $owner->getRelation($relationName);
        if (!($value instanceof $relation->modelClass)) {
            $value = $this->processModelAsArray($value, $relation, $relationName);
        }
        $this->_newRelationValue[$relationName] = $value;
        $owner->populateRelation($relationName, $value);
    }
56156
def _check_relation(self, relation):
        
        selection = [val[0] for val in self.selection]
        if relation not in selection:
            raise ValueError(
                ("The value '{value}' supplied doesn't match with the possible"
                 " values '{selection}' for the '{field_name}' field").format(
                     value=relation,
                     selection=selection,
                     field_name=self.name,
                 ))
        return relation
1220393
function (cb) {
      Model.findById(parentPk, { include: [{ all : true }]}).then(function(parentRecord) {
        if (!parentRecord) return cb({status: 404});
        if (!parentRecord[relation]) { return cb({status: 404}); }
        cb(null, parentRecord);
      }).catch(function(err){
        return cb(err);
      });
    }
1113277
public function related($relation, $column, $operator = null, $value = null, $boolean = 'and')
    {
        if ($column instanceof \Closure) {
            return $this->addRelated($relation, $column);
        }

        // If there is no value it is a where = ? query and we set the appropriate params
        if ($value === null) {
            $value = $operator;
            $operator = '=';
        }

        return $this->addRelated($relation, function ($query) use ($column, $operator, $value, $boolean) {
            return $query->where($column, $operator, $value, $boolean);
        });
    }
108129
private void onRelation(Object entity, Map<String, Object> relationsMap, final Relation relation,
            final EntityMetadata metadata, final PersistenceDelegator pd, boolean lazilyloaded,
            Map<Object, Object> relationStack)
    {
        final Object entityId = PropertyAccessorHelper.getId(entity, metadata);

        // if relation map contains value, then invoke target entity with find
        // by id.
        // else invoke target entity for find by relation, pass it's entityId as
        // a column value and relation.getJoinColumnName as column name.

        Object relationValue = relationsMap != null ? relationsMap.get(relation.getJoinColumnName(kunderaMetadata))
                : null;
        EntityMetadata targetEntityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,
                relation.getTargetEntity());

        List relationalEntities = fetchRelations(relation, metadata, pd, entityId, relationValue, targetEntityMetadata);

        if (relationalEntities != null)
        {

            for (Object relationEntity : relationalEntities)
            {
                if (relationEntity != null)
                {
                    addToRelationStack(relationStack, relationEntity, targetEntityMetadata);
                }
            }
            for (Object relationEntity : relationalEntities)
            {
                if (relationEntity != null)
                {
                    onParseRelation(entity, pd, targetEntityMetadata, relationEntity, relation, lazilyloaded,
                            relationStack);
                    PersistenceCacheManager.addEntityToPersistenceCache(getEntity(relationEntity), pd,
                            PropertyAccessorHelper.getId(relationEntity, targetEntityMetadata));
                }
            }
        }

    }
1370871
function(name, options) {
    const self = this
    const utils = self.store.utils

    // called every time before a parent query occures, with an include of this relation.
    // maybee the conditions of the parent query will contain variables whilch will let us
    // query this relation simultaneously.
    // e.g. Parent.find(99).include('children')
    //      with from: 'id' to: 'parent_id'
    //      99 => is the id!
    options.loadFromConditions =
      options.loadFromConditions ||
      function(parentCollection, parentConditions, include) {
        include = include || {}
        const conditions = utils.parentConditionsToConditions(
          parentConditions || [],
          options.from,
          options.to
        )
        if (!conditions) return

        return defaultFetch(parentCollection, conditions, include)
      }

    // called every time we need to fetch data for that relation
    options.loadFromRecords =
      options.loadFromRecords ||
      function(parentCollection, include, existingCollection) {
        include = include || {}

        const conditions = utils.recordsToConditions(
          parentCollection,
          options.from,
          options.to
        )
        if (!conditions) return Promise.resolve([]) // not enough info to form conditions. Better return an empty result instead of loading the whole dataset!

        return defaultFetch(
          parentCollection,
          conditions,
          include,
          existingCollection
        ).then(function(result) {
          // add the result to corresponding record
          parentCollection.forEach(function(record) {
            record.relations[name] = options.filterCache(record, result)
          })

          return result
        })
      }

    function defaultFetch(
      parentCollection,
      conditions,
      include,
      existingCollection
    ) {
      const relationCache = parentCollection.getInternal('relation_cache') || {}

      // return cached result, if available!
      if (relationCache[options.name]) {
        const result = relationCache[options.name]
        if (!result.then) return Promise.resolve(relationCache[options.name])
        return result
      }

      const query = options.model.where(conditions)
      if (options.conditions) query.where(options.conditions) // conditions on the relation
      if (options.scope) query[options.scope].apply(query, include.args) // scope on the relation
      if (include.conditions) query.where(include.conditions) // nested conditions via `where({relation_name: {...conditions...}})`
      if (include.children) query.include(include.children) // nested includes via `include({relation_name: {nested_relation_name: { ... }}})`
      if (include.scope) query[include.scope].apply(query, include.args) // scope defined via `include({relation_name: {$scope: 'myscope'}})`
      if (existingCollection) {
        const existingConditions = existingCollection.getInternal('conditions')
        const existingIncludes = existingCollection.getInternal('includes')

        if (existingIncludes) query.addInternal('includes', existingIncludes)
        if (existingConditions) {
          // add only new conditions
          const intConditions = query.getInternal('conditions')
          query.addInternal(
            'conditions',
            existingConditions.filter(function(c) {
              if (options.to.indexOf(c.attribute) !== -1) return false // ignore conditions with the target id field. existinCollection will automatically add such an id.

              var match = false
              intConditions.forEach(function(intC) {
                if (options.model.store.utils.compareObjects(c, intC, true))
                  match = true
              })
              return !match
            })
          )
        }

        utils.assignInternals(query, existingCollection, {
          exclude: ['relation', 'relation_to']
        })
      }

      const promise = query.then(function(result) {
        // overwrite cache result
        relationCache[options.name] = result
        return result
      })

      // store the promise in the cache object
      relationCache[options.name] = promise
      parentCollection.setInternal('relation_cache', relationCache)

      return promise
    }

    // called with every parent and child record. returns true/false for matching relations
    options.filterCache =
      options.filterCache ||
      function(parentRecord, records) {
        if (options.model) {
          const chain = options.model.chain()

          if (records) {
            if (!Array.isArray(records)) records = [records]
            const relatedRecords = records.filter(function(record) {
              var match = true

              options.from.forEach(function(key, index) {
                const opposite = options.to[index]
                const val1 = parentRecord[key]
                const val2 = record[opposite]
                if (!utils.checkFieldEquality(val1, val2)) match = false
              })
              return match
            })

            chain.add(relatedRecords) // add all child records
            chain._exists() // set this collection as existing (all records fetched from the datastore!)
          }

          chain.setInternal('relation', options) // add the parent relation of this collection
          chain.setInternal('relation_to', parentRecord) // + the parent record

          return chain
        }

        throw new Error('You need to implement your own `filterCache` function!')
      }

    options.getFromCache = function(parentRecord, include, existingCollection) {
      const parentCollection =
        parentRecord.__chainedModel ||
        parentRecord.model.chain().add(parentRecord)

      return options
        .loadFromRecords(parentCollection, include || {}, existingCollection)
        .then(function(result) {
          if (!result) return null
          return options.filterCache(parentRecord, result)
        })
    }

    return options
  }
1081991
function (name, value) {
                targeting[slot] = targeting[slot] || {};
                targeting[slot][name] = value;
            }
548844
public function addRel($relation, $value)
        {
            if (is_string($relation)) {
                $this->_rel[$relation] = $value;
            }

            return $this;
        }
879628
public void addRelation(String property, Relation relation)
    {
        relationsMap.put(property, relation);
        addRelationName(relation);
    }