M
M
mixejuxix2019-07-09 12:10:19
Laravel
mixejuxix, 2019-07-09 12:10:19

How to save a model with nested relationships?

Hey!
I have a model with nested relationships

//Псевдокод
Sites
    ->hasOne(Header::class) ['title', 'slogan']
        ->hasOne(Logo::Class)
    ->hasOne(Portfolio::Class)
        ->hasMany(PortfolioItem::Class) ['title']
            ->hasOne(Image::Class);

From the frontend I send data in json format
{  
   "id":1,
   "header":{
      "id":3 //Есть id - обновим
      "title":"Рога и копыта",
      "slogan":"Продаем и покупаем",
      "logo":{  
         "id":135,
      }
   },
   "portfolio":{  
      "PortfolioItem":[  
         {  //У этого объекта нет id - нужно вставить новый
            "image":{  
               "id":555,
            }
            "title":"Тест 1",
         },
         {  
            "id":204, //Такой объект уже существует - нужно его обновить
            "title":"Тест 2",
         }
      ]
   },
}

How to edit/create this?
Perhaps there are some tools for automatically inserting / updating a model with all relationships?
That is, I don’t want to manually save all these relationships, but find a library that itself, based on json + relationships, will save everything as it should.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
NubasLol, 2019-07-09
@NubasLol

public function save(Request $request) {
        $model = Model::query()->updateOrCreate($request->all());
        
        $this->createRelation($request->all(), $model);
    }

    public function createRelation($data, $model) {
        foreach ($data as $key => $value) {
            if (method_exists($model, $key)) {
                         $relation = $model->$key()->updateOrCreate($value);


                $this->createRelation($value, $relation);
            }
        }
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question