eloquent relationship - Laravel query model with relations, I just want the related models that meet criteria - Stack Overflow

I have a model salesperson, it has model traffic related.I am trying to return all the salespeople wi

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 badge
Add a comment  | 

1 Answer 1

Reset to default 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();

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745255649a4618938.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信