Laravel Eloquent where 关系子句与加入关系

Laravel Eloquent where clause on relationship with joining relationship

我试图向所有 用户显示他们在日期之间的积分值。点值需要介于开始日期和结束日期范围之间。我遇到的问题是我有一个 ActivityName 模型连接到 ActivityPoints 以显示类别名称。我一直都知道要在连接中为这样的事情添加一个 where 子句,但我不确定连接关系会落在哪里。

$SalesReps = User::with('ActivityPoints', function ($query) use ($StartDate, $EndDate) {
                $query->where('created_at', '>=', $StartDate);
                $query->where('created_at', '<=', $EndDate);
            }, 'ActivityPoints.ActivityName')
            ->whereIn('id', $SalesRepsData->pluck('id')->toArray())
            ->get();

这个returns错误: mb_strpos() expects parameter 1 to be string, object given

显然,我可以这样做:

$SalesReps = User::with('ActivityPoints', 'ActivityPoints.ActivityName')
            ->whereHas('ActivityPoints', function ($query) use ($StartDate, $EndDate) {
                $query->where('created_at', '>=', $StartDate);
                $query->where('created_at', '<=', $EndDate);
            })
            ->whereIn('id', $SalesRepsData->pluck('id')->toArray())
            ->get();

但它不会显示零分(空值)的用户。

谢谢!

WhereBetween 选项可以工作

$SalesReps = User::with('ActivityPoints', 'ActivityPoints.ActivityName')
    ->whereHas('ActivityPoints', function ($query) use ($StartDate, $EndDate) {
        $query->whereBetween('created_at', array($StartDate,$EndDate));
      })
    ->whereIn('id', $SalesRepsData->pluck('id')->toArray())
    ->get();

试试下面的代码。

$SalesReps = User::with('ActivityPoints', function ($query) use ($StartDate, $EndDate) {
                $query->where('created_at', '>=', $StartDate)
                ->where('created_at', '<=', $EndDate);
            }, 'ActivityPoints.ActivityName')
            ->whereIn('id', $SalesRepsData->pluck('id')->toArray())
            ->get();

在它周围添加了一个括号并且它起作用了..奇怪。

     $SalesReps = User::with(['ActivityPoints' => function ($query) use ($StartDate, $EndDate) {
            $query->where('created_at', '>=', $StartDate);
            $query->where('created_at', '<=', $EndDate);
        }], 'ActivityPoints.ActivityName')
        ->whereIn('id', $SalesRepsData->pluck('id')->toArray())
        ->get();