以下是我显示的模型,我的控制器和视图。我正在尝试将联系人保存到特定组。当我保存时,我得到错误
调用未定义的方法Illuminate \ Database \ Query \ Builder :: sync()
但是,我在我的模型中也找不到任何错误。我在这里做错了什么?
PS:laravel的初学者
组
public function contacts()
{
return $this->hasMany('App\Contact');
// ->withTimestamps();
}
与
public function groups()
{
return $this->belongsTo('App\Group');
// ->withTimestamps();
}
public function saveGroup($groups)
{
if(!empty($groups))
{
$this->groups()->sync($groups);
} else {
$this->groups()->detach();
}
}
控制器
public function store(Request $request)
{
$contact = new Contact(array(
'name' => $request->get('name'),
));
$customer->groups()->sync($request->get('group[]'));
$contact->save();
}
查看
<div class="input-field col s12">
<select class="form-control" id="group" name="group[]" mulitple>
@foreach($groups as $group)
<option value="{!! $group->id !!}" @if(in_array($group->id, $selectedGroups)) selected="selected" @endif >
{!! $group->title !!}
</option>
@endforeach
</select>
</div>
答案 0 :(得分:0)
同步功能与一对多或多对多关系相关。有关详细信息,请参阅https://laravel.com/docs/5.6/eloquent-relationships#updating-many-to-many-relationships。
我建议您将模型代码更改为
public function groups()
{
return $this->belongsToMany('App\Group');
// ->withTimestamps();
}
public function saveGroup($groups)
{
if(!empty($groups))
{
$this->groups()->sync($groups);
} else {
$this->groups()->detach();
}
}