/** * Saves the HasMany relational data. If id exists * then it updates the record otherwise it will * create the record. * * @param Model $relatedModel Model class * @param HasMany $hasMany * @param $data * @param $relationName * * @throws \Exception */ protected function saveHasManyData($relatedModel, HasMany $hasMany, $data, $relationName) { if ($this->exists) { $models = []; $pk = $hasMany->getRelated()->primaryKey; foreach ($data as $d) { /** @var Model $model */ $model = $relatedModel::find(ArrayUtils::get($d, $pk)); if (!empty($model)) { $fk = $hasMany->getPlainForeignKey(); $fkId = ArrayUtils::get($d, $fk); if (null === $fkId) { //Foreign key field is null therefore delete the child record. $model->delete(); continue; } elseif (!empty($fkId) && $fkId !== $this->{$this->primaryKey} && null !== ($parent = static::find($fkId))) { //Foreign key field is set but the id belongs to a different parent than this parent. //There the child is adopted by the supplied parent id (foreign key). $relatedData = [$relationName => [$d]]; $parent->update($relatedData); continue; } else { $model->update($d); continue; } } else { $model = new $relatedModel($d); } $models[] = $model; } $hasMany->saveMany($models); } }
/** * Get the plain foreign key. * * @return string * @static */ public static function getPlainForeignKey() { //Method inherited from \Illuminate\Database\Eloquent\Relations\HasOneOrMany return \Illuminate\Database\Eloquent\Relations\HasMany::getPlainForeignKey(); }