38

Let's say I have the following model:

class Movie extends Eloquent
{
    public function director()
    {
        return $this->belongsTo('Director');
    }
}

Now I'd like fetch movies using a where condition that's based on a column from the directors table.

Is there a way to achieve this? Couldn't find any documentation on conditions based on a belongs to relationship.

Lior
  • 5,454
  • 8
  • 30
  • 38

2 Answers2

66

You may try this (Check Querying Relations on Laravel website):

$movies = Movie::whereHas('director', function($q) {
    $q->where('name', 'great');
})->get();

Also if you reverse the query like:

$directorsWithMovies = Director::with('movies')->where('name', 'great')->get();
// Access the movies collection
$movies = $directorsWithMovies->movies;

For this you need to declare a hasmany relationship in your Director model:

public function movies()
{
    return $this->hasMany('Movie');
}

If you want to pass a variable into function($q) { //$variable } then

function($q) use ($variable) { //$variable }
Tiago Martins Peres
  • 14,289
  • 18
  • 86
  • 145
The Alpha
  • 143,660
  • 29
  • 287
  • 307
  • 3
    The first one actually works! I didn't even try it since there is no whereHas relation, but a belongsTo. Still not sure why it would work and why there isn't a whereBelongsTo condition though. – Lior Jun 02 '14 at 19:23
  • Alpha, I want to pass a variable into `function($q) { //$variable }`. How can I do that? (Error log is "the variable is undefined"). – horse Jan 14 '17 at 08:18
  • 3
    `function($q) use ($variable) { //$variable }` – The Alpha Jan 14 '17 at 08:37
  • `$movies = Movie::whereHas('director', function($q) { $q->where('name', 'great'); })->get();` **whereHas** didn't work for me instead the below code worked perfectly `$deliveries = Delivery::with(array('order' => function($query) { $query->where('orders.user_id', $customerID); $query->orderBy('orders.created_at', 'DESC'); })) ->orderBy('date') ->get();` Source : https://laravel.io/forum/08-21-2014-where-on-with-relation Laravel 5.1 – sanky Feb 14 '17 at 12:22
  • if i add in hasmany with where and pass param in movies then with movies where i can write params to pass them – sunil Nov 13 '17 at 13:11
  • Code sugar `whereRelation` https://laravel.com/docs/9.x/eloquent-relationships#inline-relationship-existence-queries `Movie::whereRelation('director', 'name', 'great');` – PayteR Mar 22 '22 at 07:04
5

whereBelongsTo()

For new versions of Laravel you can use whereBelongsTo().

It will look something like this:

$director = Director::find(1);
$movies = Movie::whereBelongsTo($director);

More in the docs.

is()

For one-to-one relations is() can be used.

$director = Director::find(1);
$movie = Movie::find(1);

$movie->director()->is($director);
mare96
  • 3,749
  • 1
  • 16
  • 28