Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eloquent Nested relations with where clause query returns collection on false condition

I am trying to search for all Rents that have a RentItem with a book title LIKE the given $input.

The problem is when the input does not match,I still get a collection returned. The only difference is that the book relation is null instead of a collection.

Result of query that should return false: https://pastebin.com/pd7UqhCi

Result of query that is true: https://pastebin.com/shndvdMh

When book equals null, I do not want the Rent model to be returned.

My query

$rents = Rent::with(['rentItems.book' => function ($query) use ($input) { 
       $query->where('books.title', 'LIKE', "%$input%"); 
}])->get();

Rent model Relation

public function rentItems()
{
  return $this->hasMany(RentItem::class);
}

RentItems model Relations

public function book()
{
     return $this->belongsTo(Book::class);
}

public function rent()
{
     return $this->belongsTo(Rent::class);
}

Research i have done:

  • https://laracasts.com/discuss/channels/laravel/eloquent-nested-relations-with-where-clause
  • https://laracasts.com/discuss/channels/eloquent/using-wherehas-and-with
  • https://laravel.com/docs/5.6/eloquent-relationships#constraining-eager-loads
like image 835
Rowan van Winden Avatar asked Mar 05 '18 14:03

Rowan van Winden


1 Answers

You need to use the whereHas() method. Do something like this:

$rents = Rent::whereHas('rentItems.book', function ($query) use ($input) { 
    $query->where('books.title', 'LIKE', "%$input%"); 
})->get();
like image 104
Alexey Mezenin Avatar answered Oct 17 '22 12:10

Alexey Mezenin