admin管理员组文章数量:1416642
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();
本文标签:
版权声明:本文标题:eloquent relationship - Laravel query model with relations, I just want the related models that meet criteria - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745255649a2650083.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论