codiaf
codiaf

Reputation: 629

Eloquent query is returning everything even with my where statement

I am trying to get some info from 2 tables with eloquent and its relationships with Constraining Eager Loads in Laravel 5.1, but it always returns everything even when the 'where' is searching for a non-existing value

This is the code:

$selectedImages = ImageSession::with(['folder' => function($query){
    $query->where('session', Session::getId());
}])->get();

I would like to also learn how to specify the select columns for this statement.

Thanks for the help

Upvotes: 1

Views: 139

Answers (1)

Joseph Silber
Joseph Silber

Reputation: 219938

You query only restricts the folders, but not image sessions.

Use the whereHas method to restrict the main model too:

$constraint = function ($query) {
    $query->where('session', Session::getId());
};

$selected = ImageSession::with(['folder' => $constraint])
                        ->whereHas('folder', $constraint)
                        ->get();

Upvotes: 1

Related Questions