【问题标题】:Filter based on collection or sub-attribute基于集合或子属性过滤
【发布时间】:2020-09-17 15:30:22
【问题描述】:

我的用户模型有一个“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 未来 prev_date 的 prevregistrations,如下所示:

$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 不起作用,因为那是属性。

谢谢

【问题讨论】:

    标签: laravel


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-06
      • 1970-01-01
      • 1970-01-01
      • 2011-08-31
      相关资源
      最近更新 更多