function addTo(Model $model, Model $relatedModel) { if (!$model->primaryKeyIsSet()) { $model->insert(); } if (!isset($this->through)) { $foreignKey = $this->foreignKey; $localKey = Model::primaryKeyName($model); $relatedModel->{$foreignKey} = $model->{$localKey}; $relatedModel->save(); } else { if (!$relatedModel->primaryKeyIsSet()) { $relatedModel->insert(); } // TODO: This is a shitshow. $through = new $this->through(); $localPrimaryKey = Model::primaryKeyName($model); $localForeignKey = $this->foreignKey; $through->{$localForeignKey} = $model->{$localPrimaryKey}; $relatedPrimaryKey = Model::primaryKeyName($this->through); $relatedForeignKey = Model::getRelationship($this->through, Inflector::toSingular($this->name))->foreignKey; $through->{$relatedForeignKey} = $relatedModel->{$relatedPrimaryKey}; $through->insert(); } return $model; }
function set(Model $model, Model $relatedModel) { if (!$relatedModel->primaryKeyIsSet()) { $relatedModel->insert(); } $foreignKey = $this->foreignKey; $relatedPrimaryKey = Model::primaryKeyName($relatedModel); $model->{$foreignKey} = $relatedModel->{$relatedPrimaryKey}; $model->save(); return $model; }