代码之家  ›  专栏  ›  技术社区  ›  Fil

尝试使用laravel获取筛选值,但工作不正常,结果错误

  •  0
  • Fil  · 技术社区  · 7 年前

    我有 users 桌子和 subscriptions 桌子

    订阅 表中有一个外键列 user_id 和其他专栏 status 类型为enum且具有一组值 ('canceled','active','skipped','unpaid','pastdue','expired')

    在模型中,我定义了它们之间的关系,

    public function subscription()
    {
        return $this->hasMany(Subscription::class);
    }
    

    现在我正在实现一个过滤器功能

    在我的dataTable类的这个函数中

    public function query(User $model)
    {
        if ($this->_filters['subscription_status']) {
            $status = $this->_filters['subscription_status'];
    
            $model = $model->whereHas('subscription', function($query) use ($status) {
                $query->where('status', $status);
            });
        }
    

    现在,当我试图获取订阅状态的用户列表时 canceled

    结果,我得到了一个状态为的用户列表 active cancelled 为什么上面的代码不起作用?

    1 回复  |  直到 7 年前
        1
  •  0
  •   Ijas Ameenudeen    7 年前

    你应该使用 with has .你可以看到不同之处。

    获取用户列表 具有 订阅状态 取消

    $model = $model->with(['subscription' => function ($query) use ($status) {
        $query->where('status', status);
    }])
    

    获取用户列表 订阅状态 取消

    $model = $model->whereHas('subscription', function($query) use ($status) {
        $query->where('status', $status);
    });