根据集合或子属性过滤

时间:2020-09-17 15:30:22

标签: laravel

我的用户模型具有'prevregistration'属性

 public function prevregistration()
{
    return $this->hasMany(Prevregistration::class, 'prevregistration_userid');
}

我的prevregistraton模型具有'prev'属性

  public function prev()
{
    return $this->hasOne(Prev::class,'prev_id', 'prevregistration_previd');
}

在我的控制器中,我显示了当前用户的预先注册:

mynextprevs = Auth::user()->prevregistration ;

现在,我只想显示将来连接的prev_date所基于的prevregistration,例如:

$mynextprevs = Auth::user()->prevregistration::whereDate('prev_date', '>=', Carbon::today()->toDateString());

但是我得到:

BadMethodCallException 方法Illuminate \ Database \ Eloquent \ Collection :: whereDate不存在。

我也这样尝试过:

$mynextprevs = Auth::user()->prevregistration->prev::whereDate('prev_date', '>=', Carbon::today()->toDateString());

但是我得到:

此集合实例上不存在属性[prev]。

我/应该如何过滤集合?我很好奇Auth :: user()-> prevregistration-> prev为什么不起作用,因为那是属性。

谢谢

1 个答案:

答案 0 :(得分:1)

您需要在预注册中使用条件whereHas

$mynextprevs = Auth::user()->prevregistration()->whereHas('prev',function($prev) {
    $prev->whereDate('prev_date', '>=', Carbon::today()->toDateString());
})->get();

请注意,我们使用该关系作为方法prevregistration()来作为查询构建器而不是集合来访问它,因此最终需要使用->get()