mardi 30 avril 2019

Laravel query relationship based on name not id

Hi I am new laravel and struggling a bit on understanding how to query 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 relationship 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 authors table. There is also a pivot table called category_books that contains category_id and book_id to link books to categories

But how do I query books so that it returns only books based on the authors name ?

I would also like to do the same thing based on the category name?

I my books controller i have the following but not sure how to do it correctly

public function index(request $request, Author $author, Category $category)
{

    $author = $request->author;

    $books = Book::find()->author()->where('name', $author);

    $books = Book::with(['categories'])->where('name', $category);

    return response()->json($books, 200);
}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire