4

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.

2 Answers 2

11

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');
}])
Sign up to request clarification or add additional context in comments.

5 Comments

thank you, this works like I wanted. Is there an easy way to be selective on the pagePhotos fields it pulls in at this point? Or do I need to narrow it on the model itself?
@weekapaug just posted an edit to my answer to help you with this
I see, but thats an "instead" scenario. Is there a way to select from both at this level? I know I can select it at the model level, but what about within the query here?
its not an instead scenario, you apply whereHas to filter and with to specify the fields you want to select from the relationship
I see, I did ->with('pagePhotos' => function($query) { $query->select('field1', 'field2')->where('photoLocation','=','Miami'); }) but I get all fields still. This is another question at this point, sorry!!
6

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.