简体   繁体   English

Laravel更新一对多关系

[英]Laravel update one to many relationship

I have two table the first is subjects table and the second is subjects_doctors table . 我有两个表,第一个是Subjects表 ,第二个是subjects_doctors表 The relationship here is One To Many . 这里的关系是一对多的

Update method code: 更新方法代码:

public function update(Request $request, $id)
    {
        $this -> validate($request, [
            'name'          => 'required',
            'max_students'  => 'required',
            'doctors'       => 'required',
            'description'   => 'required'
        ]);

        $subject = Subject::find($id);
        $subject -> name            = $request -> name;
        $subject -> description     = $request -> description;
        $subject -> max_students    = $request -> max_students;
        $subject -> save();
//PROBLEM
        $y = Subject::where('id', $subject -> id) -> doctors() -> update(['doctor_id' => $request -> doctors]);


        Session::flash('success', 'Subject has been updated successfully!');
        return redirect() -> route('subjects.index');
    }

The $request variable contain an array that have all the updated doctors id . $request变量包含一个具有所有更新的Doctors ID的数组。

For Example 例如

I have in the subjects table that subject 1 HAVE 1 DOCTOR and I have updated it to SUBJECT 1 HAVE 2 DOCTORS .. How I do that? 我在主题表中subject 1 HAVE 1 DOCTOR并且已将其更新为SUBJECT 1 HAVE 2 DOCTORS subject 1 HAVE 1 DOCTOR ..我该怎么做?

I have everything in variables but I can't update them in the subjects_doctors table. 我将所有内容都保存在变量中,但是无法在subjects_doctors表中更新它们。

The problem has been solved by using the sync() function from Laravel. 通过使用Laravel中的sync()函数已解决了该问题。 Thanks. 谢谢。

here is the code it may help 这是它可能会帮助的代码

$subject = Subject::find($id);
    $subject -> name            = $request -> name;
    $subject -> description     = $request -> description;
    $subject -> max_students    = $request -> max_students;
    $subject -> save();

    $subject -> doctors() -> sync($request -> doctors);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM