问题是当我尝试更新book
表时,它显示错误
未知专栏'出版商'
我有一个book_publisher
数据透视表。
我需要编写哪些代码以及在哪里编写代码?
class Book extends Model
{
// protected table='book';
public function authors()
{
return $this->belongsToMany(Author::class)->withPivot('type');
}
// public function author($type)
// {
//
// return $this->authors()->where('type', $type)->first();
// }
public function author()
{
return $this->authors()->where('type', 'Author')->first();
}
public function illustrator()
{
return $this->authors()->where('type', 'Illustrator')->first();
}
public function translator()
{
return $this->authors()->where('type', 'Translator')->first();
}
public function editor()
{
return $this->authors()->where('type', 'Editor')->first();
}
// foreach ($book->authors as $author)
// {
// $author->type;
// }
public function publishers()
{
return $this->belongsToMany(Publisher::class);
}
}
BookController的
public function edit($id)
{
$book=Book::findOrFail($id);
$category=Category::pluck('name', 'id');
$publishers=Publisher::all();
foreach($publishers as $publisher)
{
$publisher->id=$publisher->name;
}
return view('books.edit', compact('book','category','publishers'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$book=Book::findOrFail($id);
$book->Update($request->all());
Book::find($id)->publisher()->updateExistingPivot($request->only('publisher_id'));
return redirect('books');
}
还请告诉我是否还要编辑edit.blade.php。
答案 0 :(得分:0)
检查这些方法
$books = Book::find($id);
$books->publisher()->updateExistingPivot('publisher_id',
['publisher_id' => publisher_id],false));
或类似的东西
$books = Book::find($id);
$publisher = $books->publisher;
$publisher->pivot->publisher_id = $request->publisher_id;
$publisher->pivot->save();