mardi 30 avril 2019

Laravel Associate with relationship and create if not exists

Hi I am new laravel and struggling a bit on understanding how to create relationships. I am trying to make a basic restful api in laravel and have 3 models

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

Table migrations:

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 is the main table and author has a one to many relationships with books. Category has a many to many relationship with books as a book can be in more than one category.

The books table has an author_id field to link it to the author's table. There is also a pivot table called category_books that contains category_id and book_id to link books to categories.

Say I want to create a new book record and if the author exists to associate the book to that author but it if doesn't exist I want to create a new author record and then associate the book to that author?

I would also like to be able to do the same thing with categories

I have the following in my 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);
    }



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire