对我所拥有的内容的简短解释:
使用名为ManyOnMany
的数据透视表在project
和user
之间建立project_user
关系。
在显示某个项目时,会打印一个用户列表,并选中复选框,以便在选中该复选框后立即将其链接到项目(因此它会将user_id
+ project_id
发送给pivot table
现在问题。当我们将用户(例如Admin der Liam
)链接到项目时它将起作用并且数据将被发送到数据库。
但是当再次取消选中该复选框时,它将发出Call to a member function users() on a non-object
错误,而不是清除表并仅将选中的框放入数据库
控制器:
public function edit($id, Project $project)
{
$users = User::with('projects')->get();
$project = $this->project->find($id);
return view('project.edit', ['project' => $project, 'id' => 'edit', 'project_id' => $id, 'users' => $users]);
}
public function update(CreateProjectRequest $request)
{
if($request->get('contribute'))
{
foreach($request->get('contribute') as $k => $contribute)
{
if($contribute == 1)
{
$project = $this->project->find($request->project_id);
$keys[] = $k;
}
}
}
$project->users()->sync($keys);
$project = $this->project->find($request->project_id);
$project->fill($request->input())->save();
return redirect('project');
}
HTML /刀片:
@if(isset($users))
@foreach($users as $user)
<tr>
<td>
{{$user->firstname}} {{$user->middlename}} {{$user->lastname}}
</td>
<td>
{!! Form::checkbox('contribute['.$user->id.']', '1', $user->projects->contains($project->id)) !!}
</td>
</tr>
@endforeach
@endif
答案 0 :(得分:0)
你的$项目是空的,因为你在foreach中声明了$ project。 尽量在foreach之外宣布它。
答案 1 :(得分:0)
将$project->users()->sync($keys);
放在while循环中$project = $this->project->find($request->project_id);
之后。
初始化对象后,应该同步$项目。
foreach($request->get('contribute') as $k => $contribute)
{
if($contribute == 1)
{
$project = $this->project->find($request->project_id);
$keys[] = $k;
$project->users()->sync($keys);
}
}
答案 2 :(得分:0)
public function update(CreateProjectRequest $request)
{
$this->project = $this->project->find($request->project_id);
if($request->get('contribute'))
{
foreach($request->get('contribute') as $k => $contribute)
{
if($contribute == 1)
{
$keys[] = $k;
}
}
}
if(isset($keys)) {
$this->project->users()->sync($keys);
}
else {
$this->project->users()->detach();
}
$this->project = $this->project->find($request->project_id);
$this->project->fill($request->input())->save();
return redirect('project');
}