Join other related objects into a collection for the purpose of filtering. Relationships
is either a flat array of relationships (as defined in the object's schema) or a nested array
@chainable
435012
public function join($rels, $joinType='inner')
    {
        $schemaAlias = $this->_schema->alias();

        foreach (Relationship::normalizeMap($rels) as $alias=>$nested) {
            Relationship::addJoin($this->_queryForWrite(),
                $schemaAlias, $this->_schema, $alias, $nested, $joinType);
        }

        return $this;
    }
174300
function(record, json, relationship) {
        var attr = relationship.key;
        var belongsTo = record.belongsTo(attr);
        var type, key;

        if (isNone(belongsTo)) {
          return;
        }

        type = this.keyForSnapshot(belongsTo);
        key = this.keyForRelationship(attr);

        if (!json.links) {
          json.links = json.relationships || {};
        }
        json.links[key] = belongsToLink(key, type, get(belongsTo, 'id'));
      }
106795
public function initRelation(array $models, $relation)
    {
        foreach ($models as $model)
        {
            // In the case of fetching nested relations, we will get an array
            // with the first key being the model we need, and the other being
            // the related model so we'll just take the first model out of the array.
            if (is_array($model)) $model = reset($model);

            $model->setRelation($relation, $this->related->newCollection());
        }

        return $models;
    }
437720
private function models() {
		$relationships = $dates = [];
		$tables = config('center.tables');

		//loop through once to create relationships between tables
		foreach ($tables as $table) {

			$dates[$table->name] = [];

			if (!isset($relationships[$table->name])) $relationships[$table->name] = [];
			
			foreach ($table->fields as $field) {
				
				//define relationships
				if ($field->type == 'checkboxes') {
	
					//out from this object
					$order_by = [];
					foreach ($tables[$field->source]->order_by as $column=>$direction) {
						$order_by[] = '->orderBy("' . $column . '", "' . $direction . '")';
					}
					$relationships[$table->name][] = '
					public function ' . $tables[$field->source]->name . '() {
						return $this->belongsToMany("LeftRight\Center\Models\\' . $tables[$field->source]->model . '", "' . $field->name . '", "' . RowController::formatKeyColumn($table->name) . '", "' . RowController::formatKeyColumn($tables[$field->source]->name) . '")' . implode($order_by) . ';
					}
					';
				
					//back from the related object
					$order_by = [];
					foreach ($table->order_by as $column=>$direction) {
						$order_by[] = '->orderBy("' . $column . '", "' . $direction . '")';
					}
					$relationships[$tables[$field->source]->name][] = '
					public function ' . $table->name . '() {
						return $this->belongsToMany("LeftRight\Center\Models\\' . $table->model . '", "' . $field->name . '", "' . RowController::formatKeyColumn($tables[$field->source]->name) . '", "' . RowController::formatKeyColumn($table->name) . '")' . implode($order_by) . ';
					}
					';	

				} elseif (in_array($field->type, ['date', 'datetime'])) {

					$dates[$table->name][] = '\'' . $field->name . '\'';
				
				} elseif ($field->type == 'image') {

					//cannot overwrite property
					$relationships[$table->name][] = '
					public function ' . substr($field->name, 0, -3) . '() {
						return $this->hasOne("LeftRight\Center\Models\File", "id", "' . $field->name . '");
					}
					';
				
				} elseif (in_array($field->type, ['select', 'user'])) {
					
					//public function ' . $tables[$field->source]->name . '() {

					//out from this object
					$relationships[$table->name][] = '
					public function ' . substr($field->name, 0, -3) . '() {
						return $this->belongsTo("LeftRight\Center\Models\\' . $tables[$field->source]->model . '", "' . $field->name . '");
					}
					';
	
					//back from the related object
					$relationships[$tables[$field->source]->name][] = '
					public function ' . $table->name . '() {
						return $this->hasMany("LeftRight\Center\Models\\' . $table->model . '", "' . $field->name . '");
					}
					';
				}
			}
		}
		
		//debug
		//dd($relationships);

		//now we must loop through again; the first loop set relationships on other tables
		foreach ($tables as $table) {
			eval('namespace LeftRight\Center\Models;
			use Illuminate\Database\Eloquent\SoftDeletes;
			use Auth;
			use DateTime;
			use DB;
			use Eloquent;

			class ' . $table->model . ' extends Eloquent {
			    ' . (isset($table->fields->deleted_at) ? 'use SoftDeletes;' : '') . '
				public $table      = \'' . $table->name . '\'; //public intentionally
				public $timestamps = false; //going to override if present
				protected $guarded = [];
				protected $dates   = [' . implode(',', $dates[$table->name]) . '];

				public static function boot() {
					parent::boot();
			        static::creating(function($object) {' . 
				        (isset($table->fields->precedence) ? '
						$object->precedence = DB::table(\'' . $table->name . '\')->max(\'precedence\') + 1;
						' : '') .
				        (isset($table->fields->created_by) ? '
						$object->created_by = Auth::id();
						' : '') .
				        ($table->timestamps && isset($table->fields->created_at) ? '
						$object->created_at = new DateTime();
						' : '') .
				        (isset($table->fields->updated_by) ? '
						$object->updated_by = Auth::id();
						' : '') .
				        ($table->timestamps && isset($table->fields->updated_at) ? '
						$object->updated_at = new DateTime();
						' : '') . 
					'});
			        static::updating(function($object) {' . 
			        	(isset($table->fields->updated_by) ? '
						$object->updated_by = Auth::id();
						' : '') .
				        ($table->timestamps && isset($table->fields->updated_at) ? '
						$object->updated_at = new DateTime();
						' : '') . 
			        '});
				}

				public function creator() {
					return $this->belongsTo(\'User\', \'created_by\');
				}

				public function updater() {
					return $this->belongsTo(\'User\', \'updated_by\');
				}

				' . implode(' ', $relationships[$table->name]) . '
			}');
			
		}

	}
1191502
function defineRelationshipResolution(
  schema: GraphQLSchema,
  relationships: Relationship[],
  database: DatabaseInterface,
): void {
  relationships.forEach(relationship => {
    defineFieldResolve(
      schema,
      relationship.path[0].fromType,
      relationship.fieldName,
      database.generateRelationshipResolver(relationship),
    );
  });
}
231760
private function fillRelationshipAsSingleResource($data, $relationship, $key)
    {
        $data['data']['relationships'][$key] = $relationship[0];

        if ($this->shouldIncludeLinks()) {
            $data['data']['relationships'][$key] = array_merge([
                'links' => [
                    'self' => "{$this->baseUrl}/{$data['data']['type']}/{$data['data']['id']}/relationships/$key",
                    'related' => "{$this->baseUrl}/{$data['data']['type']}/{$data['data']['id']}/$key",
                ],
            ], $data['data']['relationships'][$key]);

            return $data;
        }
        return $data;
    }
818543
public List getPrefetchedRelationships()
	{
        // BRJ:
        // combine data from query and criteria
        // TODO: to be removed when Criteria#addPrefetchedRelationship is removed
        ArrayList temp = new ArrayList();
        temp.addAll(m_prefetchedRelationships);

        if (getCriteria() != null)
        {
            temp.addAll(getCriteria().getPrefetchedRelationships());
        }

        return temp;
    }
140343
def relationships
      r = Relationships.new
      r << Relationship.new(cache_definition, PIVOT_TABLE_CACHE_DEFINITION_R, "../#{cache_definition.pn}")
      r
    end
744105
function getRelated() {
  var relatedValues = getValue(this, 'see');
  if (relatedValues && relatedValues.trim().length > 0) {
    var relatedItems = relatedValues.split(',').map((relatedItem) => relatedItem.trim());
    return relatedItems.map((relatedItem) => '[' + relatedItem + '](#' + relatedItem + ')');
  } else {
    return [];
  }
}
1345534
def related_model(self):
        
        relationship_field = self.name

        if relationship_field not in get_relationships(self.schema):
            raise InvalidFilters("{} has no relationship attribute {}".format(self.schema.__name__, relationship_field))

        return getattr(self.model, get_model_field(self.schema, relationship_field)).property.mapper.class_
54769
private function initRelations() {
    if ($this->relations == null) {
      $this->relations = [];
      $this->relations['byrole'] = [];
      $this->relations['bytype'] = [];

      $relations = $this->getRelations();
      foreach ($relations as $relation) {
        $this->relations['byrole'][$relation->getOtherRole()] = $relation;
        $otherType = $relation->getOtherType();
        if (!isset($this->relations['bytype'][$otherType])) {
          $this->relations['bytype'][$otherType] = [];
        }
        $this->relations['bytype'][$otherType][] = $relation;
        $this->relations['bytype'][$this->persistenceFacade->getSimpleType($otherType)][] = $relation;
      }
    }
  }
588457
function(data, payload) {
        var type = data.length > 0 ? data[0].type : null;
        var serializer = this;
        data.forEach(function(item) {
          if(item.relationships) {
            serializer.extractRelationships(item.relationships, item);
          }
        });

        payload[type] = data;
      }
1296811
function ( relationships, deformerNodes ) {

			var rawBones = [];

			relationships.children.forEach( function ( child ) {

				var boneNode = deformerNodes[ child.ID ];

				if ( boneNode.attrType !== 'Cluster' ) return;

				var rawBone = {

					ID: child.ID,
					indices: [],
					weights: [],
					transform: new THREE.Matrix4().fromArray( boneNode.Transform.a ),
					transformLink: new THREE.Matrix4().fromArray( boneNode.TransformLink.a ),
					linkMode: boneNode.Mode,

				};

				if ( 'Indexes' in boneNode ) {

					rawBone.indices = boneNode.Indexes.a;
					rawBone.weights = boneNode.Weights.a;

				}

				rawBones.push( rawBone );

			} );

			return {

				rawBones: rawBones,
				bones: []

			};

		}
1181210
def set_relationships(module_names, module_ids, link_field_names, related_ids)
    login! unless logged_in?
    
    [module_names, module_ids, link_field_names, related_ids].each do |arg|
      raise ArgumentError, "argument must be an Array" unless arg.class == Array
    end
    
    json = <<-EOF
      {
        "session": "#{@sugar_session_id}",
        "module_names": "#{module_names.to_json}",
        "module_ids": #{module_ids.to_json},
        "link_field_names": #{link_field_names.to_json},
        "related_ids": #{related_ids.to_json}   
      }
    EOF
    json.gsub!(/^\s{6}/,'')
    send!(:set_relationships, json)
  end
674762
function get_associated_collections(collection) {
  const map = new Map()

  get_association_keys(collection)
    // Return the identity to the related resource.
    .forEach(key => {
      // Get the attributes
      const collection_attributes = collection._attributes[key]

      // Most of the time, it's a one to one
      // relationship so it's not an array.
      let is_array = false

      // But sometimes, it's a one to many
      // so array must be true.
      if (collection_attributes.hasOwnProperty("collection")) {
        is_array = true
      }

      // Set the values.
      map.set(key, { is_array, collection })
    })

  return map
}
716070
def _nested_relations(self, relation):
        
        nested = {}

        for name, constraints in self._eager_load.items():
            if self._is_nested(name, relation):
                nested[name[len(relation + ".") :]] = constraints

        return nested
370556
public function getRelationships()
    {
        $relationships = array();

        foreach ($this->getProperty() as $name => $property) {
            if ($property->isRelationship()) {
                $relationships[$name] = $property;
            }
        }

        return $relationships;
    }