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?
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?
Share Improve this question asked Feb 2 at 21:34 Chris LambChris Lamb 11 bronze badge1 Answer
Reset to default 2The 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();
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745255649a4618938.html
评论列表(0条)