-1

I have a model salesperson, it has model traffic related. I am trying to return all the salespeople with traffic in a given month and get ONLY the traffic from that month.

Right now it is returning the collection, but also returning all traffic related to that salesperson, even those results where month and year don't match.

The traffic model has a column "date_for", and I only want to return the traffic where "date_for" is the specified month and year.

My query is:


$date = new DateTime(now(), new DateTimeZone("America/New_York"));
$day = $date->format("d");
$month = $date->format("m");
$year = $date->format("Y");

$salespeople = Salesperson::with("traffic", "store")
  ->whereHas("traffic", function ($query) use ($month, $year) {
    $query->whereMonth("date_for", $month)->whereYear("date_for", $year);
  })
  ->get();

How do I get just the traffic models returned with the salesperson that meet the year and month values?

1 Answer 1

2

The problem is that you're telling Eloquent to only return instances of Salesperson that have a traffic relation that matches your criteria (whereHas), but to also load all traffic (with).

Luckily, Laravel has a withWhereHas method which adds the same constraint to both the whereHas and with.

You can update your code to be this:

$salesPeople = Salesperson::with('store')
    ->withWhereHas('traffic', function (Builder $query) use($month, $year) {
        $query->whereMonth('date_for', $month)->whereYear('date_for', $year);
    });
    ->get();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.