(Mysql) how do i update parent and its reference in backend?
take a look at this table first then i'll explain.
parent {
id:number;
name:string;
}
child {
id:number;
name:string;
parent_id:number; //foreignKey to parent table
}
and this is the API request to do an update to backend
Request = {
id:1; //parent id
name:'update the name';
childs:[
{
id:1,
name:'child 1'
},
{
id:null, //if null its mean i have to create this child
name:'child 2'
}
]
}
so if the Request.childs have id on each item then i have to update the child, but if its doesn't have an id i have to create a new child.
And if child doesn't exist in Request.childs i have to delete it.
my question is how do i delete the previous child that doesn't exist in Request.childs ?
what i am doing now is i am deleting all the child that belongs to the parent_id and create a new child based on Request, but since child have soft delete on all the deleted child will get stacked in the database.
what currently i am doing
{
child::where('parent_id',Request->id)->delete();
foreach($Request->childs as $item){
child::create['name'=>$item->name,'parent_id'=>$Request->id];
}
}
what i probably i have to do
foreach($Request->childs as $item){
if($item->id == null){
child::create['name'=>$item->name,'parent_id'=>$Request->id];
}
child::find($item->id)->update['name'=>$item->name];
}
i just don't know how to delete the previous child record without deleting everything ?
from Recent Questions - Stack Overflow https://ift.tt/2TCLlka
https://ift.tt/eA8V8J
Comments
Post a Comment