weekapaug
weekapaug

Reputation: 332

Laravel Query using with() statement

Having trouble trying to use the with statement on a query as shown here

thePage::select('field1','field2')
->with('pagePhotos')

This query works fine, but what if I want to only get pagePhotos where the photoLocation="Miami". This photoLocation field is not on thePage Model, and only on the pagePhotos table.

Below is a stab in the dark that doesn't work but it shows the logic I'm trying to get at, I hope!

thePage::select('field1','field2')
->with(
    'pagePhotos'->where('photoLocation','=','Miami')
)->get();

EDIT

In addition to the answer / comments here I found this helped me get the query perfect https://stackoverflow.com/a/41436703/7675570

Just in case anyone has similar scenarios it could help.

Upvotes: 4

Views: 17790

Answers (2)

Seva Kalashnikov
Seva Kalashnikov

Reputation: 4392

Use whereHas:

thePage::select('field1','field2')
    ->with('pagePhotos')
    ->whereHas('pagePhotos', function($query) {
        $query->where('photoLocation', '=', 'Miami');
    })
    ->get();

Laravel Querying Relationship Existence

Edit:

If you want to be selective on the pagePhotos fields, instead of

->with('pagePhotos')

do pass param as array

->with(['pagePhotos' => function($query) {
    $query->select('field1', 'field2');
}])

Upvotes: 10

Duy Huynh
Duy Huynh

Reputation: 291

I think you should handle the query by using a closure.

thePage::select('field1','field2')->with(array('pagePhotos' => function($query) {
        $query->where('photoLocation','=','Miami');
}))->get();

Hope it can help you

Upvotes: 6

Related Questions