欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

laravel one to many sync 一对多 attaceh 同步保存 有大用 有大大用

attach  增加(其实一对多当中是没有attach方法的),附加 见 /node-admin/9182


sync 同步保存见如下

一对多中 也是没有sync 方法 


It seems like there is no sync() function for morph tables on Laravel.

I have two tables avails and questionsquestions is a morphMany table. I want to use the sync command, and this is what I did:

Avail::find($id)->questions()->sync($some_ids);




正确答案


1)把原来的外键置为空

$questionsOld = $avail->questions()->
get(); $questionsOld->each(function ($question) {  // appropriate fields here:  // 1*  $question->FOREIGN_ID = null;  $question->FOREIGN_TYPE = null;  $question->save(); });
//再取出所有副表的对象 $questionsNew =
Question::whereIn('id', $someIds)->get();
2)进行保存 saveMany
// *2 $avail->questions()->saveMany($questionsNew->getDictionary());
(
2)我的方法是直接update副表的外键 先得到所有副表,然后再update) Category::whereIn('category_id',$request->input('category_guanxi'))->update(['category_guanxi'=>$category->category_id]);


普通分类: