reza
reza

Reputation: 1507

Laravel Eloquent hasMany Specific Relationship Row Return

I have 2 tables with following sample data

Courses

id cl1
1 a
2 b

Offers

id course_id year
1 1 2019
2 1 2020
3 2 2019

in the respective model one to many relationship is defined normally(works fine)

I want to select course with offers of a certain year value only with the selected relationship only.

when i try the following code it gives me correct course table row but returns both id 1 and 2 of the offers table in the relationship.

Course::with(['offer'])
            ->whereHas('offer', function ($q) {
                $q->where('year',2020);
            })                
            ->get();

how can i get only the selected relationship(for this example id 2 only).

fyi: Due to some other need i can not use Offer::with(['course'])

Upvotes: 0

Views: 43

Answers (1)

MichalOravec
MichalOravec

Reputation: 1708

You need to use same logic for eager loading

Course::with(['offer' => function ($query) {
    $query->where('year', 2020);
}])->whereHas('offer', function ($query) {
    $query->where('year', 2020);
})->get();

It could be simplified by saving a closure to the variable

Course::with(['offer' => $closure = function ($query) {
    $query->where('year', 2020);
}])->whereHas('offer', $closure)->get();

Upvotes: 1

Related Questions