首页 > 解决方案 > 计算注册类型价格 > 0 的会议中的注册

问题描述

我有一个查询来计算会议中的注册数量:

    $registrationsCount = $conference->registrations->count();

但我只想获得与价格> 0 的注册类型相关的会议注册。你知道如何实现吗?例如,如果会议“测试会议”有两种注册类型“rt1 和 rt2”,rt1 的价格为 0,rt2 的价格为 10,并且注册类型“rt2”中有 5 个注册,则查询应返回 5 ,因为会议有5个付费注册。

会议模式:

 public function registrationTypes(){
        return $this->hasMany('App\RegistrationType', 'conference_id');
    }

    public function registrations(){
        return $this->hasMany('App\Registration', 'conference_id');
    }

注册型号:

 public function registration_types(){
        return $this->belongsToMany('App\RegistrationType', 'registration_registration_types');
    }


public function conference(){
    return $this->belongsTo('App\Conference');
}

注册类型型号:

   public function conference(){
        return $this->belongsTo('App\Conference');
    }

public function registrations(){
        return $this->belongsToMany('App\Registration', 'registration_registration_types');
    }

参与者型号:

public function registration(){
    return $this->belongsTo('App\Registration');
}


public function registration_type(){
    return $this->belongsTo('App\RegistrationType');
}

表结构:

conferences: id, name
registrations: id, status, conference_id, user_that_did_registration
registration_types: id, name, price, conference_id 
participants: id, registration_id, registration_type_id, name

标签: laravel

解决方案


老实说,我并没有完全理解你的要求,但我看到了以下两种可能性:

Conference::whereHas('registrationTypes', function ($query) {
        $query->where('price', '>', 0);
    })
    ->withCount('registrations')
    ->get();

// will give you something like this
[
  {
    "id": 1,
    "name": "Laracon",
    "registrations_count": 100
  }
]

或者,您可以在计数中执行价格检查

Conference::withCount(['registrations' => function ($query) {
        $query->whereHas('registration_types', function ($query) {
            $query->where('price', '>', 0);
        });
    }])
    ->get();

推荐阅读