在注册类型价格> 0的会议中对注册进行计数

时间:2018-07-02 13:03:04

标签: laravel

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

    $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

3 个答案:

答案 0 :(得分:2)

说实话,我不完全理解您的要求,但我看到以下两种可能性:

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();

答案 1 :(得分:1)

您可以这样:

$count = Registration::whereHas('registration_types', function($q) use($user) {
                            $q->where('price ', '>', 0);
                        })
                    ->where('conference_id', $conferenceId)
                    ->count();

答案 2 :(得分:0)

尝试此代码

$conference->registrations->sum(function ($registration) {
    $registrationTypes = $registration->registration_types->where('price', '>', 0);
    return $registrationTypes ? $registrationTypes->count() : 0;
});