What about moving that fetchAllFlocksByDateAndId to the the Flock model? A tradeoff is that we have a join a few more tables, should be fine:
class Flock extend Model
{
public static function fetchAllFlocksByDateAndId($farm_id, $date)
{
return static::select('flocks.*')
->where('started_at', "<=", $date)
->where(function (Builder $query) use ($date) {
$query->whereNull('ended_at')
->orWhere('ended_at', ">=", $date);
})
->where('farms.id', $farm_id)
->join('salons', 'salons.id', '=', 'flocks.salon_id')
->join('farms', 'farms.id', '=', 'salons.farm_id')
->get();
}
}
Alternatively, we can do inline relationship existence queries:
class Flock extend Model
{
public function salons()
{
return $this->belongsTo(Salon::class);
}
public static function fetchAllFlocksByDateAndId($farm_id, $date)
{
return static::select('flocks.*')
->where('started_at', "<=", $date)
->where(function (Builder $query) use ($date) {
$query->whereNull('ended_at')
->orWhere('ended_at', ">=", $date);
})
->whereRelation('salons', 'farm_id', $farm_id)
->get();
}
}