[英]Laravel Associate with relationship and create if not exists
嗨,我是新來的laravel,在理解如何建立關系方面有些掙扎。 我正在嘗試在laravel中創建一個基本的Restful API並具有3個模型
class Book extends Model {
public function author()
{
return $this->belongsTo(Author::class);
}
public function categories()
{
return $this->belongsToMany('App\Category', 'category_book')
->withTimestamps();
}
}
class Author extends Model
{
public function books(){
return $this->hasMany(Book::class);
}
}
class Category extends Model
{
public function books()
{
return $this->belongsToMany('App\Book', 'category_book')
->withTimestamps();
}
}
表遷移:
Schema::create('books', function (Blueprint $table) {
$table->engine = "InnoDB";
$table->increments('id');
$table->string('ISBN', 32);
$table->string('title');
$table->integer('author_id')->unsigned();
$table->float('price')->default(0);
$table->timestamps();
});
Schema::create('authors', function (Blueprint $table) {
$table->engine = "InnoDB";
$table->bigIncrements('id');
$table->string('name');
$table->string('surname');
$table->timestamps();
});
Schema::create('categories', function (Blueprint $table) {
$table->engine = "InnoDB";
$table->bigIncrements('id');
$table->string('name');
$table->timestamps();
});
Schema::create('category_book', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('category_id')->unsigned();
//$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
$table->integer('book_id')->unsigned();
//$table->foreign('book_id')->references('id')->on('books')->onDelete('cascade');
$table->timestamps();
});
書籍是主要的表格,作者與書籍具有一對多的關系。 類別與書籍具有多對多的關系,因為一本書可以屬於多個類別。
books表具有一個author_id字段,可將其鏈接到作者的表。 還有一個名為category_books的數據透視表,其中包含category_id和book_id,用於將書籍鏈接到類別。
假設我要創建一個新的書記錄,並且如果存在作者以將該書與該作者相關聯,但是如果不存在,我想創建一個新的作者記錄,然后將該書與該作者相關聯?
我也希望能夠對類別執行相同的操作
我的bookscontroller中具有以下內容:
public function store(Request $request)
{
$book = new book;
$book->title = $request->title;
$book->ISBN = $request->ISBN;
$book->price = $request->price;
$book->categories()->associate($request->category);
$book->save();
return response()->json($book, 201);
}
首先,在行中
$book->categories()->associate($request->category);
當您要更新一個belongsTo
關系時,使用方法associate()
。 $ book-> categories()是一個多對多關系( belongsToMany
),因此您應該使用attach()
代替。
其次,如果要關聯可能存在或不存在的作者,則可以使用firstOrCreate
方法。
$author = Author::firstOrCreate([
'name' => $request->author_name,
'surname' => $request->author_surname
]);
$book->author()->associate($author);
您可以使用“類別”或“書籍”來做同樣的事情。
$category = Category::firstOrCreate([
'name' => $request->category_name
]);
$book->categories()->attach($category);
$book = Book::firstOrCreate([
'ISBN' => $request->book_isbn,
'title' => $request->book_title,
'price' => $request->book_price
]);
$category->books()->attach($book);
https://laravel.com/docs/5.8/eloquent#other-creation-methods此處記錄了firstOrCreate()
的使用。此頁面上有更多關於雄辯關系方法的信息https://laravel.com/docs/5.8/eloquent-關系
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.