Render relation methods

@return string
960792
public function renderRelationMethods()
    {
        $output = '';

        foreach ($this->relations as $relation) {
            $output .= $relation->renderMethod();
        }

        return $output;
    }
807050
public function getRelations()
    {
        if (!isset($this->relationships)) {
            $this->relationships = array();
            // load them manually
            $mm = $this->getModelsManager();
            $relationships = $mm->getRelations(get_class($this));
            // Temporary fix because $mm->getRelations() doesn't support hasManyToMany relations right now.
            // get them separately and merge them
            $mtmRelationships = $mm->getHasManyToMany($this);

            $relationships = array_merge($relationships, $mtmRelationships);

            foreach ($relationships as $relation) {
                // todo load custom relationship
                $this->relationships[] = new Relation($relation, $mm);
            }
        }
        return $this->relationships;
    }
396639
protected function generateRelations()
	{
		$this->_relations=array();
		$this->_classes=array();
		foreach($this->_schema->getTables() as $table)
		{
			$tableName=$table->name;

			if ($this->isRelationTable($table))
			{
				$pks=$table->primaryKey;
				$fks=$table->foreignKeys;

				$table0=$fks[$pks[1]][0];
				$table1=$fks[$pks[0]][0];
				$className0=$this->getClassName($table0);
				$className1=$this->getClassName($table1);

				$unprefixedTableName=$this->removePrefix($tableName,true);

				$relationName=$this->generateRelationName($table0, $table1, true);
				$this->_relations[$className0][$relationName]="array(self::MANY_MANY, '$className1', '$unprefixedTableName($pks[0], $pks[1])')";

				$relationName=$this->generateRelationName($table1, $table0, true);
				$this->_relations[$className1][$relationName]="array(self::MANY_MANY, '$className0', '$unprefixedTableName($pks[0], $pks[1])')";
			}
			else
			{
				$this->_classes[$tableName]=$className=$this->getClassName($tableName);
				foreach ($table->foreignKeys as $fkName => $fkEntry)
				{
					// Put table and key name in variables for easier reading
					$refTable=$fkEntry[0]; // Table name that current fk references to
					$refKey=$fkEntry[1];   // Key in that table being referenced
					$refClassName=$this->getClassName($refTable);

					// Add relation for this table
					$relationName=$this->generateRelationName($tableName, $fkName, false);
					$this->_relations[$className][$relationName]="array(self::BELONGS_TO, '$refClassName', '$fkName')";

					// Add relation for the referenced table
					$relationType=$table->primaryKey === $fkName ? 'HAS_ONE' : 'HAS_MANY';
					$relationName=$this->generateRelationName($refTable, $this->removePrefix($tableName), $relationType==='HAS_MANY');
					$this->_relations[$refClassName][$relationName]="array(self::$relationType, '$className', '$fkName')";
				}
			}
		}
	}
1208635
public function relations()
    {
        $email = Yii::app()->getModule('email');
        if (!empty($email->modelMap[get_class($this)]['relations']))
            return $email->modelMap[get_class($this)]['relations'];
        return parent::relations();
    }
509567
public function render()
    {
        $parser = new ClassParser($this->reflectionClass);
        $methods = $parser->getMethodsDetails();
        ksort($methods);

        $this->setData(
            [
                'className' => $this->reflectionClass->getName(),
                'classShortName' => $this->reflectionClass->getShortName(),
                'methods' => $methods,
                'classDescription' => $parser->getClassDescription(),
                'interfaces' => $parser->getInterfaces(),
                'parentClass' => $parser->getParentClassName(),
                'inheritedMethods' => $parser->getInheritedMethods(),
            ]
        );
        return parent::render();
    }
198182
public function toArray()
    {
        $relations = [];
        $arrayableRelations = [];

        // include any relations exposed by default
       foreach ($this->exposedRelations as $relation) {
            // skip loading a relation if it is from a method
            if (in_array($relation, $this->relationsFromMethod)) {
                // if the relation hasnt been loaded, then load it
                if (!isset($this->$relation)) {
                    $this->$relation = $this->$relation();
                }

                $arrayableRelations[$relation] = $this->$relation;
                continue;
            }

            $this->load($relation);
        }

        // fetch the relations that can be represented as an array
        $arrayableRelations = array_merge($this->getArrayableRelations(), $arrayableRelations);

        // add the relations to the linked array
        foreach ($arrayableRelations as $relation => $value) {
            if (in_array($relation, $this->hidden)) {
                continue;
            }

            if ($value instanceof Pivot) {
                continue;
            }

            if ($value instanceof BaseModel) {
                $relations[$relation] = array('linkage' => array('id' => (string)$value->getKey(), 'type' => $value->getResourceType()));
            } elseif ($value instanceof Collection) {
                $relation = \str_plural($relation);
                $items = ['linkage' => []];
                foreach ($value as $item) {
                    $items['linkage'][] = array('id' => (string)$item->getKey(), 'type' => $item->getResourceType());
                }
                $relations[$relation] = $items;
            }

            // remove models / collections that we loaded from a method
            if (in_array($relation, $this->relationsFromMethod)) {
                unset($this->$relation);
            }
        }

        //add type parameter
        $model_attributes = $this->attributesToArray();
        unset($model_attributes[$this->primaryKey]);

        $attributes = [
            'id'         => (string)$this->getKey(),
            'type'       => $this->getResourceType(),
            'attributes' => $model_attributes
        ];

        if (! count($relations)) {
            return $attributes;
        }

        return array_merge(
            $attributes,
            [ 'links' => $relations ]
        );
    }
593365
private function buildRelationshipGetters() {
        $buffer = '';
        foreach($this->getRelationships() as $relationship) {
            $field = $this->getField($relationship->getLocalColumn());
            if($relationship->isPlural()) {
                $method = new Object\Method();
                $method->setAccess('public');
                $method->setDescription('Gets the related ' . $relationship->getAlias());
                $method->setName('get' . ucfirst($relationship->getAlias()));
                $method->setReturnType('ResultSet|Child' . $relationship->getRemoteShortModel() . '[]');
                $parameter = new Object\Parameter();
                $parameter->setDescription('');
                $parameter->setName('parameters');
                $parameter->setDefaultValue('null');
                $parameter->setType('array');
                $method->addParameter($parameter);
                $method->setContent('return $this->getRelated(\'' . $relationship->getAlias() . '\', $parameters);');
                $this->getAbstractClass()->addMethod($method);

                $method = new Object\Method();
                $method->setAccess('public');
                $method->setDescription('Gets the count of related ' . $relationship->getAlias());
                $method->setName('count' . ucfirst($relationship->getAlias()));
                $method->setReturnType('int');
                $parameter = new Object\Parameter();
                $parameter->setDescription('');
                $parameter->setName('parameters');
                $parameter->setDefaultValue('null');
                $parameter->setType('array');
                $method->addParameter($parameter);
                $method->setContent('return $this->get' . ucfirst($relationship->getAlias()) . '($parameters)->count();');
                $this->getAbstractClass()->addMethod($method);
            } else {

                $method = new Object\Method();
                $method->setAccess('public');
                $method->setDescription('Gets the related ' . $relationship->getAlias());
                $method->setName('get' . ucfirst($relationship->getAlias()));
                if($this->getAbstractClass()->hasMethod($method->getName())) {
                    $method->setName('getRelated' . ucfirst($relationship->getAlias()));
                }
                $method->setReturnType('Child' . $relationship->getRemoteShortModel() . '|false');
                $method->setContent('return $this->getRelated(\'' . $relationship->getAlias() . '\');');
                $this->getAbstractClass()->addMethod($method);

                if($field->isNullable()) {
                    $method = new Object\Method();
                    $method->setAccess('public');
                    $method->setDescription('Checks if a relationship exists');
                    $method->setName('has' . ucfirst($relationship->getAlias()));
                    $method->setReturnType('bool');
                    $method->setContent('return !is_null($this->get' . ucfirst($relationship->getAlias()) . '());');
                    $this->getAbstractClass()->addMethod($method);
                }
            }
        }
        return $buffer;
    }
786137
protected function getRelationMethodSection(array $relationships, $type = CmsModel::RELATION_TYPE_MODEL)
    {
        $replace = '';

        $relatedClassName = $this->context->getModelNamespaceForSpecialModel($type);

        foreach ($relationships as $name => $relationship) {

            $relationParameters       = '';
            $relationMethodParameters = '';

            if ($relationKey = array_get($relationship, 'key')) {
                $relationParameters = ", '{$relationKey}'";
            }

            if (    array_get($relationship, 'translated')
                &&  $type !== CmsModel::RELATION_TYPE_MODEL
                &&  config('pxlcms.generator.models.allow_locale_override_on_translated_model_relation')
            ) {
                $relationMethodParameters = '$locale = null';

                // skip parameters not entered, pass on the optional locale key
                $relationParameters = (substr_count($relationParameters, ',') ? null : ', null')
                                    . ', null'
                                    . ', $locale';
            }

            $replace .= $this->tab() . "public function {$name}({$relationMethodParameters})\n"
                      . $this->tab() . "{\n"
                      . $this->tab(2) . "return \$this->{$relationship['type']}({$relatedClassName}::class"
                      . $relationParameters
                      . ");\n"
                      . $this->tab() . "}\n"
                      . "\n";


            if ($type == CmsModel::RELATION_TYPE_IMAGE) {
                // since images require special attention for resize enrichment,
                // add an accessor method that will take care of it (through some magic)
                $replace .= $this->tab() . "public function get" . studly_case($name) . "Attribute()\n"
                          . $this->tab() . "{\n"
                          . $this->tab(2) . "return \$this->getImagesWithResizes();\n"
                          . $this->tab() . "}\n"
                          . "\n";
            }

        }

        return $replace;
    }
222690
public function render()
	{
		if ($this->getDisplayField() === null) {
			throw new \InvalidArgumentException(sprintf('Please provide a display field for the `%s` relation.', $this->getName()));
		}

		switch ($this->getContext()) {
			case BaseField::CONTEXT_LIST:
				$baseModel    = $this->getAdmin()->getModel();
				$baseModel    = new $baseModel;

				$relatedModel = $baseModel->{$this->getName()}()->getRelated();
				$primaryKey   = $relatedModel->getKeyName();

				$values = [];
				foreach ($this->getValue() as $item) {
					$values[$item->{$primaryKey}] = $item->{$this->getDisplayField()};
				}

				return implode(', ', $values);

				break;
			case BaseField::CONTEXT_FORM:
				$baseModel  = $this->getAdmin()->getModel();
				$baseModel  = new $baseModel;
				$primaryKey = $baseModel->getKeyName();

				$relatedModel = $baseModel->{$this->getName()}()->getRelated();

				$items = [];
				foreach ($relatedModel::all() as $item) {
					$items[$item->{$primaryKey}] = $item->{$this->getDisplayField()};
				}

				$id = $this->getAdmin()->getFormBuilder()->getIdentifier();
				$values = [];

				if ($id !== null) {
					foreach ($baseModel::find($id)->{$relatedModel->getTable()} as $item) {
						$values[$item->{$primaryKey}] = $item->{$primaryKey};
					}
				}

				return View::make('krafthaus/bauhaus::models.fields._belongs_to_many')
					->with('field',  $this)
					->with('items',  $items)
					->with('values', $values);
		}
	}
639890
public function render()
	{
		if ($this->getDisplayField() === null) {
			throw new \InvalidArgumentException(sprintf('Please provide a display field for the `%s` relation via the display(); method.', $this->getName()));
		}

		switch ($this->getContext()) {
			case BaseField::CONTEXT_LIST:
				$value = $this->getValue();
				return $value->{$this->getDisplayField()};
				break;

			case BaseField::CONTEXT_FILTER:
                $baseModel  = $this->getAdmin()->getModel();
                $baseModel  = new $baseModel;
				$primaryKey = $baseModel->getKeyName();

                $relatedModel = $baseModel->{$this->getName()}()->getRelated();

                $items = [];
                foreach ($relatedModel::all() as $item) {
                    $items[$item->{$primaryKey}] = $item->{$this->getDisplayField()};
                }

                $column = Str::singular($relatedModel->getTable()) . '_id';
                if (Input::has($column)) {
                    $this->setValue(Input::get($column));
                }

				return View::make('krafthaus/bauhaus::models.fields._belongs_to')
					->with('field', $this)
					->with('items', $items);
				break;

			case BaseField::CONTEXT_FORM:
				$baseModel  = $this->getAdmin()->getModel();
				$baseModel  = new $baseModel;
				$primaryKey = $baseModel->getKeyName();

				$relatedModel = $baseModel->{$this->getName()}()->getRelated();

				$items = [];
				foreach ($relatedModel::all() as $item) {
					$items[$item->{$primaryKey}] = $item->{$this->getDisplayField()};
				}

				if ($this->getValue() !== null) {
					$this->setValue($this->getValue()->{$primaryKey});
				}

				return View::make('krafthaus/bauhaus::models.fields._belongs_to')
					->with('field', $this)
					->with('items', $items);

				break;
		}

		return $this->getValue();
	}
883292
public function loadRelations() {
        foreach ([
            Relation::MANY_TO_ONE => $this->belongsTo,
            Relation::MANY_TO_MANY => $this->belongsToMany,
            Relation::ONE_TO_ONE => $this->hasOne,
            Relation::ONE_TO_MANY => $this->hasMany
        ] as $type => $relations) {
            foreach ($relations as $alias => $relation) {
                if (is_string($relation)) {
                    $relation = ['model' => $relation];
                }

                $relation = $relation + [
                    'model' => null,
                    'foreignKey' => null,
                    'relatedForeignKey' => null,
                    'conditions' => null,
                    'junction' => null
                ];

                switch ($type) {
                    case Relation::MANY_TO_ONE:
                        $this->belongsTo($alias, $relation['model'], $relation['foreignKey'], $relation['conditions']);
                    break;
                    case Relation::MANY_TO_MANY:
                        $this->belongsToMany($alias, $relation['model'], $relation['junction'], $relation['foreignKey'], $relation['relatedForeignKey'], $relation['conditions']);
                    break;
                    case Relation::ONE_TO_ONE:
                        $this->hasOne($alias, $relation['model'], $relation['relatedForeignKey'], $relation['conditions']);
                    break;
                    case Relation::ONE_TO_MANY:
                        $this->hasMany($alias, $relation['model'], $relation['relatedForeignKey'], $relation['conditions']);
                    break;
                }
            }
        }

        return $this;
    }
996468
protected function getRelationMethods(array $relations, array $fields)
    {
        $methods = [];

        foreach ($fields as $field) {
            if ($field->hasForeignRelation()) {
                $relation = $field->getForeignRelation();
                $methods[$relation->name] = $this->getRelationshipMethod($relation);
            }
        }

        foreach ($relations as $relation) {
            $methods[$relation->name] = $this->getRelationshipMethod($relation);
        }

        return $methods;
    }
386562
private function buildRelationshipsBuffer() {
        $buffer = '';
        foreach($this->getRelationships() as $relationship) {
            $buffer .= '		$this->' . $relationship->getRelationshipType() . '(
			\'' . $this->getField($relationship->getLocalColumn())->getShortName() . '\',
			\'' . $relationship->getRemoteModel() . '\',
			\'' . $relationship->getRemoteShortColumn() . '\',
			array(
				\'alias\'      => \'' . $relationship->getAlias() . '\',
				\'foreignKey\' => array(
					\'message\' => \'The ' . $this->getTableName() . ' cannot be deleted because other ' . $relationship->getRemoteTable() . '(s) are attached\',
					\'action\'  => Relation::' . $relationship->getAction() . '
				),
				\'reusable\' => true
			)
		);' . "\n";
        }
        return $buffer;
    }
278884
public function render()
    {
        if (is_callable($this->builder)) {
            call_user_func($this->builder, $this);
        }

        if ($this->fields->isEmpty()) {
            $this->all();
        }

        if (is_array($this->builder)) {
            $this->fields($this->builder);
        }

        $this->fields->each->setValue($this->model);
        $this->relations->each->setModel($this->model);

        $data = [
            'panel'     => $this->panel->fill($this->fields),
            'relations' => $this->relations,
        ];

        return view('admin::show', $data)->render();
    }
536786
public function render()
    {
        // Always add this class
        $this->addClass('autocomplete');

        // Make the hidden field.  Render it before we (might) set the value to
        // the title of the parent.
        $hidden = $this->renderHidden();

        // If there is a value and the field name matches a relationship on function
        // on the current item, then get and display the title text for the related
        // record
        if ($parent = $this->parentModel()) {
            $this->value = $parent->getAdminTitleAttribute();

        // Else, if there is no parent (it's a create page), set the value if a
        // title was set
        } elseif ($this->title) {
            $this->value = $this->title;
        }

        // Add the hidden field and return
        return parent::render().$hidden;
    }
1113627
function renderRelated(relatedList, relatedTitle, classPrefix) {
    var relatedDiv = $('<div>');
    relatedDiv.addClass(classPrefix + '-container');
    relatedTitleDiv = $('<div>');
    relatedTitleDiv.addClass(classPrefix + '-container-title');
    relatedTitleDiv.text(relatedTitle);
    relatedDiv.append(relatedTitleDiv);

    $.each(relatedList, function(index, relatedPipelineId) {
      var relatedInfoMap = STATUS_MAP.pipelines[relatedPipelineId];
      if (relatedInfoMap) {
        var relatedLink = $('<a>');
        relatedLink
            .addClass(classPrefix + '-link')
            .attr('title', 'ID #' + relatedPipelineId)
            .attr('href', '#pipeline-' + relatedPipelineId)
            .text(relatedInfoMap.classPath);
        relatedLink.click(function(event) {
            selectPipeline(relatedPipelineId);
            event.preventDefault();
        });
        relatedDiv.append(relatedLink);
      } else {
        var relatedIdDiv = $('<div>');
        relatedIdDiv
            .addClass(classPrefix + '-pipeline-id')
            .text('ID #' + relatedPipelineId);
        relatedDiv.append(relatedIdDiv);
      }
    });

    return relatedDiv;
  }
854580
private function relationData()
    {
        $onData = collect($this->data)->reject(function ($value, $key) {
            return !str_contains($key, 'on');
        });

        $foreignKeys = collect($this->data)->reject(function ($value, $key) {
            return !str_contains($key, 'tbl');
        });

        $this->onData = array_values($onData->toArray());

        $this->foreignKeys = array_values($foreignKeys->toArray());
    }