To filter the families relationship based on a year value, you can use the whereHas method in combination with the with method. This allows you to add constraints to the related models.
Here's how you can modify your query to include only families that have a specific year value:
$year = 2022; // Replace this with the variable year value you want to filter by
$partners = Partner::where("public", 1)
->where("active", 1)
->whereHas('families', function ($query) use ($year) {
$query->where('year', $year);
})
->with(['families' => function ($query) use ($year) {
$query->where('year', $year);
}])
->withSum('families as people', 'people')
->orderBy('partners.site', 'ASC')
->get();
Explanation:
-
whereHas: This method filters thePartnermodels to include only those that have relatedFamilymodels with the specified year. -
with: This method ensures that only theFamilymodels with the specified year are eager-loaded. -
use ($year): This allows the closure to access the$yearvariable.
By using both whereHas and with with the same condition, you ensure that:
- Only
Partnermodels withFamilymodels matching the year are retrieved. - Only the
Familymodels matching the year are included in the eager-loaded results.
This approach allows you to dynamically change the year value and get the desired results.