Friday, March 31, 2017

Laravel eager loading combine where for multiple tables

I have problem with Laravel eager loading, I want to search many to one related tables.

I have two models, Book and Author. I have relation belongsTo (in Book model) and hasMany (in Author model).

Books: id, title, description, author, tags, type Author: id, name, birth, tags, type (this is not the real columns, I have a lot of columns, this is only for example)

I must to use models for searching, I can't use DB or raw queries for the relations.

So, my question is how can I search by parent table into Model->with() function ?

Model->with('author', function($query) use($search) {
    $query->where('author.name', '=', $search);
    $query->orWhere('book.title', '=', $search);
});

The important thing is that I need to get Books, and I must to be able to use $book->author (or on $results->toArray() to get all Book data with Author data in ->author property)

I hope that you understand me what I want to ask.

Best regards



via Damjan Krstevski

Advertisement