【问题标题】:Laravel Creating relationship while updatingLaravel 在更新时创建关系
【发布时间】:2018-05-18 14:35:57
【问题描述】:

我有一个带有学生和图书模型的图书馆管理系统。表的结构是

学生桌

id | roll_no | name | created_at | updated_at

图书桌

book_id | name | author | publication | student_id | created_at | updated_at

这里,boook_id 是主键

关系如下

书本模型

public function student()
{
    return $this->belongsTo('App\Student');
}

在学生模型中

public function books()
{
    return $this->hasMany('App\Book');
}

最初,books 表中的student_idnull。每当要发行一本书时,都会提供book number 和学生roll number,并且books 表中的student_id 字段会更新为要向其发行的学生的id

在控制器中,我有以下代码

public function postIssue(Request $request)
{
    $this->validate($request, [ 
        'rollno' => 'required|min:7',
        'bookno' => 'required|numeric',
    ]);
    $roll = $request->input('rollno');
    $bookno = $request->input('bookno');

    $student = Student::where('roll_no','=',$roll);
    $book = Book::where('book_id','=',$bookno);
    $book->student_id = $student->id;
    $book->save();
    
    return view('book.issue')->with('msg','Book Issued');
}

运行此代码时,我收到一条错误消息
"Undefined property: Illuminate\Database\Eloquent\Builder::$id"

出了什么问题?
有更好的方法吗?

我正在使用 Laravel 5.6

【问题讨论】:

    标签: php laravel laravel-5 eloquent


    【解决方案1】:
    $student = Student::where('roll_no','=',$roll)->first();
    $book = Book::where('book_id','=',$bookno)->first();
    

    像这样改变希望它会起作用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-27
      • 1970-01-01
      相关资源
      最近更新 更多