Exemplo n.º 1
1
 /**
  * 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);
     }
 }
Exemplo n.º 2
0
 /**
  * Add multiple objects through a HasMany relation
  *
  * @param \Illuminate\Database\Eloquent\Relations\HasMany $relation
  * @param \Illuminate\Support\Collection $objects
  * @return array|\Traversable
  */
 protected function addHasManyAssociatedObject(HasMany $relation, SupportCollection $objects)
 {
     return $relation->saveMany($objects);
 }
Exemplo n.º 3
0
 /**
  * Attach a collection of models to the parent instance.
  *
  * @param \Illuminate\Database\Eloquent\Collection|array $models
  * @return \Illuminate\Database\Eloquent\Collection|array
  * @static
  */
 public static function saveMany($models)
 {
     //Method inherited from \Illuminate\Database\Eloquent\Relations\HasOneOrMany
     return \Illuminate\Database\Eloquent\Relations\HasMany::saveMany($models);
 }