Get the pivot attribute from a model.

@param  \Illuminate\Database\Eloquent\Model  $model
@param  \Illuminate\Database\Eloquent\Relations\Relation  $parentRelation
967146
public static function loadPivotAttribute(Model $model, Relation $parentRelation = null)
    {
        $attributes = $model->getAttributes();

        foreach ($attributes as $key => $value) {
            if ($key === 'pivot') {
                unset($model[$key]);
                $pivot = $parentRelation->newExistingPivot($value);
                $model->setRelation($key, $pivot);
            }
        }
    }
115352
public function newRelatedInstanceFor(Model $parent)
    {
        $newInstance = $this->related->newInstance();

        if (is_array($this->localKey)) { //Check for multi-columns relationship
            $foreignKey = $this->getForeignKeyName();

            foreach ($this->localKey as $index => $key) {
                $newInstance->setAttribute($foreignKey[$index], $parent->{$key});
            }
        } else {
            return $newInstance->setAttribute($this->getForeignKeyName(), $parent->{$this->localKey});
        }
    }
1013548
public static function fromAttributes(Model $parent, $attributes, $table, $exists = false)
    {
        $instance = new static;

        $instance->timestamps = $instance->hasTimestampAttributes($attributes);

        // The pivot model is a "dynamic" model since we will set the tables dynamically
        // for the instance. This allows it work for any intermediate tables for the
        // many to many relationship that are defined by this developer's classes.
        $instance->setConnection($parent->getConnectionName())
            ->setTable($table)
            ->forceFill($attributes)
            ->syncOriginal();

        // We store off the parent instance so we will access the timestamp column names
        // for the model, since the pivot model timestamps aren't easily configurable
        // from the developer's point of view. We can use the parents to get these.
        $instance->pivotParent = $parent;

        $instance->exists = $exists;

        return $instance;
    }
556735
public function setModel(Model $model)
    {
        parent::setModel($model);

        if ($model->exists) {
            $this->setInstance($model);
            $this->loadRelationValues();
        }
    }
483149
protected function _changeParent(Model $model, $id = null, $parentId = null) {
		$parentField = $this->_getBehaviorConfig($model, 'parent');
		if (empty($id) || ($parentField === null)) {
			return false;
		}

		$model->recursive = -1;
		$treeItem = $model->read(null, $id);
		if (empty($treeItem)) {
			return false;
		}

		$treeItem[$model->alias][$parentField] = $parentId;
		$result = (bool)$model->save($treeItem);

		return $result;
	}
942366
public function associate($model, $attributes = array())
    {
       $otherKey = ($model instanceof Model ? $model->getAttribute($this->otherKey) : $model);

        $this->parent->setAttribute($this->foreignKey, $otherKey);

        if ($model instanceof Model) {
            $this->parent->setRelation($this->relation, $model);
        }

        return $this->parent;
    }
414188
public static function getRelationWidgetOptions($model, $relation, $activeRelation, $multiple = false)
    {
        /** @var \netis\crud\db\ActiveRecord $relModel */
        $relModel = new $activeRelation->modelClass;
        list($createRoute, $searchRoute, $indexRoute) = FormBuilder::getRelationRoutes(
            $model,
            $relModel,
            $activeRelation
        );

        if ($indexRoute === null) {
            return self::getRelationWidgetStaticOptions($model, $relation, $activeRelation, $multiple);
        }

        $isMany = $activeRelation->multiple;
        $foreignKeys = array_values($activeRelation->link);
        $foreignKey = reset($foreignKeys);
        $dbColumns = $model->getTableSchema()->columns;
        $primaryKey = $relModel::primaryKey();

        if (($labelAttributes = $relModel->getBehavior('labels')->attributes) !== null) {
            $fields = array_merge($primaryKey, $labelAttributes);
        } else {
            $fields = $primaryKey;
        }

        $value = self::getRelationValue($model, $relation, $activeRelation);
        $allowClear = $multiple || $isMany ? true : !$model->isAttributeRequired($foreignKey)
            && (!isset($dbColumns[$foreignKey]) || $dbColumns[$foreignKey]->allowNull);

        $jsPrimaryKey = json_encode($primaryKey);
        $jsSeparator = \netis\crud\crud\Action::COMPOSITE_KEY_SEPARATOR;
        $jsId = <<<JavaScript
function(object){
    var keys = $jsPrimaryKey, values = [];
    for (var i = 0; i < keys.length; i++) {
         values.push(object[keys[i]]);
    }
    return netis.implodeEscaped('$jsSeparator', values);
}
JavaScript;

        // check if only one option is available and if yes - set it as selected value
        if (!$allowClear && trim($value) === '') {
            $checkedRelations = $relModel->getCheckedRelations(Yii::$app->user->id, $activeRelation->modelClass . '.read');
            $relQuery = $relModel::find()
                ->select($primaryKey)
                ->from($relModel::tableName() . ' t')
                ->authorized($relModel, $checkedRelations, Yii::$app->user->getIdentity())
                ->asArray();
            if ($relQuery->count() === 1) {
                $value = $relQuery->one();
                $value = Action::implodeEscaped(Action::KEYS_SEPARATOR, $value);
            }
        }

        $label = null;
        if ($model instanceof \netis\crud\db\ActiveRecord) {
            $label = $model->getRelationLabel($activeRelation, Html::getAttributeName($relation));
        }
        $ajaxResults = new JsExpression('s2helper.results');
        $clientEvents = null;
        if ($indexRoute !== null && ($searchRoute !== null || $createRoute !== null)) {
            list ($ajaxResults, $clientEvents) = self::getRelationAjaxOptions(
                $searchRoute,
                $createRoute,
                $jsPrimaryKey,
                $label,
                $relation
            );
        }

        //we get prefix from $relation because it could be in format [3]relation and we need to have [3]foreign_key here
        $relationName = Html::getAttributeName($relation);
        $prefixedFk = str_replace($relation, $foreignKey, $relationName);
        return [
            'class' => 'maddoger\widgets\Select2',
            'model' => $model,
            'attribute' => $isMany ? $relation : $prefixedFk,
            'clientOptions' => array_merge(
                [
                    'formatResult' => new JsExpression('s2helper.formatResult'),
                    'formatSelection' => new JsExpression('s2helper.formatSelection'),
                    'id' => new JsExpression($jsId),
                    'width' => '100%',
                    'allowClear' => $allowClear,
                    'closeOnSelect' => true,
                    'initSelection' => new JsExpression($multiple ? 's2helper.initMulti' : 's2helper.initSingle'),
                    'ajax' => [
                        'url' => Url::toRoute(array_merge($indexRoute, [
                            '_format' => 'json',
                            'fields' => implode(',', $fields),
                        ])),
                        'dataFormat' => 'json',
                        'quietMillis' => 300,
                        'data' => new JsExpression('s2helper.data'),
                        'results' => $ajaxResults,
                    ],
                ],
                $multiple ? ['multiple' => true] : []
            ),
            'clientEvents' => $clientEvents,
            'options' => [
                'class' => 'select2',
                'value' => $value,
                'placeholder' => self::getPrompt(),
                //for now handle relations with single column primary keys
                'data-relation-pk' => count($primaryKey) === 1 ? reset($primaryKey) : null,
            ],
        ];
    }
78485
public function associate($model)
    {
        $this->parent->setAttribute($this->foreignKey, $model->getKey());

        $this->parent->setAttribute($this->morphType, $model->getMorphClass());

        return $this->parent->setRelation($this->relation, $model);
    }
118923
protected function getRelationData(Relation $modelRelation)
    {
        if ($this->parent && !$modelRelation->isSelfRelation() && get_class($this->parent) == get_class($modelRelation->getModel())) {
            $value = $this->parent;
        } else {
            // 获取关联数据
            $value = $modelRelation->getRelation();
        }

        return $value;
    }
1161155
public function getRelationCountQuery(Builder $query, Builder $parent)
	{
		if ($parent->getQuery()->from == $query->getQuery()->from)
		{
			return $this->getRelationCountQueryForSelfRelation($query, $parent);
		}

		return parent::getRelationCountQuery($query, $parent);
	}
1048576
public function parentModel()
    {
        if ($this->value
            && ($relation = $this->guessRelation())
            && ($model = $this->getModel())
            && method_exists($model, $relation)) {
            return $model->$relation;
        }
    }
974136
protected function getRelationType()
    {
        list($model, $attribute) = $this->resolveModelAttribute($this->valueFrom);
        return $model->getRelationType($attribute);
    }
1319445
public function associate($model)
    {
        $ownerKey = $model instanceof Model ? $model->getAttribute($this->ownerKey) : $model;

        $this->child->setAttribute($this->foreignKey, $ownerKey);

        if ($model instanceof Model) {
            $this->child->setRelation($this->relationName, $model);
        } elseif ($this->child->isDirty($this->foreignKey)) {
            $this->child->unsetRelation($this->relationName);
        }

        return $this->child;
    }
390805
public function edgeFromRelationWithDirection(Relationship $relation, Model $parent, Model $related, $direction)
    {
        // If the direction is of type 'any' we need to figure out the relationship direction
        // from the determined relation.
        if ($direction == 'any')
        {
            $direction = $this->directionFromRelation($relation, $parent, $related);
        }

        // Based on the direction we are now able to construct the edge class name and call for
        // an instance of it then pass it the actual relationship that was previously found.
        $class = $this->getEdgeClass($direction);
        $edge = new $class($this->query, $parent, $related, $relation->getType());
        $edge->setRelation($relation, true);

        return $edge;
    }
1362982
public static function findRelatedElement(Model $model, $type=null)
	{
		if($model->bootstrap_parentId == '' && $model->getType() != $model::TYPE_START) {
			return null;
		}

		$options = array(
			'order' => 'sorting'
		);

		if($type === null) {
			$column   = 'bootstrap_parentId';
			$values[] = $model->id;
		}
		else {
			$column   = array('bootstrap_parentId=? ', 'type=?');
			$values[] = $model->id;
			$values[] = $model->getTypeName($type);

		}

		return \ContentModel::findOneBy($column, $values, $options);
	}
123102
public function associate($model, $attributes = array())
    {
        /**
         * For associated models we will need to create a unique relationship
         * between the parent and the related model. In Cypher we can use the
         * MERGE clause to make sure that the relationship doesn't happen more than once.
         *
         * An example query would be like:
         *
         * HasOne:
         * -------
         *
         * MATCH (user:`User`), (phone:`Phone`)
         * WHERE id(user) = 10892 AND id(phone) = 98522
         * MERGE (user)-[rel:PHONE]-(phone)
         * RETURN rel;
         *
         * BelongsTo:
         * ---------
         *
         * MATCH (account:`Account`), (user:`User`)
         * WHERE id(account) = 10892 AND id(user) = 98522
         * MERGE (account)<-[rel:ACCOUNT]-(user)
         * RETURN rel;
         */

        // Set the relation on the model
        $this->parent->setRelation($this->relation, $model);

        /**
         * Due to the fact that relationships in Graph are entities themselves
         * we will need to treat them as such and in this case what we're looking for is
         * a relationship with an INCOMING direction towards the parent node, in other words
         * it is a relationship with an edge incoming towards the $parent model and we call it
         * an "Edge" relationship.
         */
        return $this->getEdge($model, $attributes);
    }
74244
public function findRootParentRecursively(string $parentProperty, string $table, Model $instance, bool $returnInstanceIfNoParent = true)
    {
        if (!$instance || !$instance->{$parentProperty}
            || null === ($parentInstance = $this->findModelInstanceByPk($table, $instance->{$parentProperty}))) {
            return $returnInstanceIfNoParent ? $instance : null;
        }

        return $this->findRootParentRecursively($parentProperty, $table, $parentInstance);
    }