Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Query using with() statement

Tags:

php

mysql

laravel

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.

like image 232
weekapaug Avatar asked Oct 17 '25 11:10

weekapaug


2 Answers

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');
}])
like image 74
Seva Kalashnikov Avatar answered Oct 19 '25 01:10

Seva Kalashnikov


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

like image 22
Duy Huynh Avatar answered Oct 18 '25 23:10

Duy Huynh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!