doukun8670 2018-05-18 06:21
浏览 49
已采纳

Laravel在更新时创建关系

I have a library management system with Student and Book model. The structure of the tables are

Students Table

id | roll_no | name | created_at | updated_at

Books Table

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

Here, boook_id is the primary key

The relation is as follows

In Book Model

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

In Student Model

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

Initially the student_id in books table is null. Whenever a book is to be issued, book number and student roll number is supplied and the student_id field in books table is updated with the id of the student to whom it is being issued.

In the controller, I have the following code

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');
}

When I run this codes, I get a error saying
"Undefined property: Illuminate\Database\Eloquent\Builder::$id"

What is going wrong?
Is there a better way of doing this?

I am using Laravel 5.6

  • 写回答

1条回答 默认 最新

  • dongshan0202405 2018-05-18 06:23
    关注
    $student = Student::where('roll_no','=',$roll)->first();
    $book = Book::where('book_id','=',$bookno)->first();
    

    change like this way hope it will work .

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Error in check.length("fill") : 'gpar'成分'fill'的长度不能为零
  • ¥15 python:excel数据写入多个对应word文档
  • ¥60 全一数分解素因子和素数循环节位数
  • ¥15 ffmpeg如何安装到虚拟环境
  • ¥188 寻找能做王者评分提取的
  • ¥15 matlab用simulink求解一个二阶微分方程,要求截图
  • ¥30 乘子法解约束最优化问题的matlab代码文件,最好有matlab代码文件
  • ¥15 写论文,需要数据支撑
  • ¥15 identifier of an instance of 类 was altered from xx to xx错误
  • ¥100 反编译微信小游戏求指导