Answer the question
In order to leave comments, you need to log in
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);
{
"id":1,
"header":{
"id":3 //Есть id - обновим
"title":"Рога и копыта",
"slogan":"Продаем и покупаем",
"logo":{
"id":135,
}
},
"portfolio":{
"PortfolioItem":[
{ //У этого объекта нет id - нужно вставить новый
"image":{
"id":555,
}
"title":"Тест 1",
},
{
"id":204, //Такой объект уже существует - нужно его обновить
"title":"Тест 2",
}
]
},
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question