简体   繁体   中英

Laravel eloquent relation query multiple

I have a model with a relation table and a pivot table.

Books

id name

1 book 1

2 book 2

3 book 3

Types

id name

1 fiction

2 nonfiction

3 magazine

4 hardback

5 journal

6 comedy

BookwithType

book_id type_id

1 2

1 3

2 2

2 4

as you can see a book can have more than one type, now what i want to do is a query to search for all of the types a book may have based on user input. for example if a user searches for a non fiction magazine book i would want book 1 to be returned.

at the moment my code is returning both book 1 and 2 - because book 2 is a non fiction book however it should not return unless BOTH conditions are met.

current code

$search = ['nonfiction','magazine'];

$books = Book::whereHas('types', $filter = function($query) use ($search){$query->whereIn('name',$search);
})
->get();

model

    public function types()
    {
        return $this->belongsToMany('App\Type');
    }


i can achieve my results with this function in the model however i am not able to pass a variable in this way, how can I do it?


        return $this->belongsToMany('App\Book')->wherePivotIn('type_id', [1,2]);

in your book model make hasMany relation with booktype table by bookid

use App\Book;//in top of your model
     public function bookWithType() {
            return $this->hasMany(Book::class, 'book_id');
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM