我有一些迁移书籍,用户,类别,作者和文件
我为书和文件制作了一个数据透视表,“ book_file”表:
public function up()
{
Schema::create('book_files', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('book_id');
$table->unsignedInteger('file_id');
$table->foreign('book_id')
->references('id')
->on('books')
->onDelete('cascade')
->onUpdate('cascade');
$table->foreign('file_id')
->references('id')
->on('files')
->onDelete('cascade')
->onUpdate('cascade');
$table->timestamps();
});
}
和Book型号代码:
public function files(){
return $this->belongsToMany(File::class,'files','book_files');
}
文件模型代码:
protected $fillable = [
'name',
];
public function books()
{
return $this->belongsTo(Book::class);
}
BookController:
public function create()
{
$categories = Category::all();
$authors = Author::all();
$files= File::all();
return view('books.create', compact('categories','authors','files'));
}
public function store(Request $request)
{
$this->validate($request,
[
'name'=>'required|string|max:256',
'pages'=>'required|integer|numeric',
'ISBN'=>'required|string|numeric',
'price'=>'required|integer|numeric',
'published_at'=>'required|date|date',
'file'=>'required',
]
);
if ($request->hasFile('file')) {
$filename = $request->file('file')->getClientOriginalName();
$request->file->storeAs('public', $filename);
$file = new File;
$file->name = $filename;
$file->save();
}
$book = Auth::User()->books()->create($request->except('_token'));
$book->categories()->attach($request->get('category_id'));
$book->authors()->attach($request->get('author_id'));
$book->files()->attach($request->get('file_id'));
return redirect('/books');
}
在数据库中上传的文件可以正常运行,但是我的数据透视表(book_file)不变!怎么了? 我是laravel的初学者,请帮助,谢谢。