详细信息
型号:**父母[条款和等级] **结:: (型号:term_level,表格:term_levels) >
TermModel:
public function level(){
return $this->belongsToMany(Level::class, 'term_levels','Term_id', 'Level_id');
}
LevelModel:
public function term(){
return $this->belongsToMany(Term::class, 'term_levels', 'Level_id', 'Term_id');
}
控制器:
public function store_term_level(Request $request)
{
$data=$request->all();
foreach($data['Term_id'] as $termId){
$term = Term::find($termId);
$levelids = $data['Level_id'];
$term->level()->attach($levelids);
$term_level=new term_level;
$term_level->Term_id=$request->input('Term_id');
$term_level->Level_id=$request->input('Level_id');
$term_level->save();
}
答案 0 :(得分:4)
尝试此代码
public function store_term_level(Request $request)
{
$data = $request->all();
foreach ($data['Term_id'] as $termId) {
foreach ($data['Level_id'] as $levelId) {
$term_level = new term_level;
$term_level->Term_id = $termId;
$term_level->Level_id = $levelId;
$term_level->save();
}
}
}
或
$terms = Term::whereIn('id', $data['Term_id'])->get();
foreach ($terms as $term) {
$levelids = $data['Level_id'];
$term->level()->attach($levelids);
}
答案 1 :(得分:1)
$terms = Term::whereIn('id', $data['Term_id'])->get();
foreach ($terms as $term) {
$levelids = $data['Level_id'];
$term->level()->attach($levelids);
}
这是一个更好的解决方案,因为它对数据库的请求较小
答案 2 :(得分:-1)
这是正确的答案,我将其转换为jason_array
$data=$request->all();
foreach($data['Term_id'] as $term){
$term = Term::find($term);
$level = $data['Level_id'];
$term->level()->attach($level);
$term_level=new term_level;
$term_level->Term_id=$request->input('Term_id');
$term_level->Level_id=$request->input('Level_id');
//this code solve the problem..
$term_level = json_encode($data, true);
}