Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eloquent where condition based on a "belongs to" relationship

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.

like image 351
Lior Avatar asked May 31 '14 13:05

Lior


People also ask

What is with () in Laravel?

with() function is used to eager load in Laravel. Unless of using 2 or more separate queries to fetch data from the database , we can use it with() method after the first command. It provides a better user experience as we do not have to wait for a longer period of time in fetching data from the database.

Why we use whereHas in Laravel?

whereHas() works basically the same as has() but allows you to specify additional filters for the related model to check.


2 Answers

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 } 
like image 60
The Alpha Avatar answered Oct 01 '22 01:10

The Alpha


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); 
like image 28
mare96 Avatar answered Oct 01 '22 01:10

mare96