Laravel与关系建立联系,如果不存在则创建

时间:2019-04-30 15:40:08

标签: php laravel laravel-5 eloquent

嗨,我是新来的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是主要的表格,作者与书籍具有一对多的关系。类别与书籍有很多关系,因为一本书可以属于多个类别。

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

1 个答案:

答案 0 :(得分:1)

首先,在一行中

$book->categories()->associate($request->category);

要更新associate()关系时使用方法belongsTo。 $ 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);

此处记录了firstOrCreate()的使用 https://laravel.com/docs/5.8/eloquent#other-creation-methods 此页面上有更多关于雄辩关系方法的信息 https://laravel.com/docs/5.8/eloquent-relationships