用计数和按组查询

时间:2018-06-25 00:02:11

标签: laravel eloquent

我想在视图中有一个表,该表显示与会议相关的所有注册类型,每个会议的价格以及每种注册类型的已售注册数量。

例如,如果ID为“ 1”的会议有两种注册类型,其列和值如下:

  • rtype1(名称),0.00 $(价格),20(容量)
  • rtype2(名称),5.00 $(价格),10(容量)

在rtype1中注册了20位参与者,在rtype 2中注册了5位参与者,我想显示一个表格,如下所示:

Registration Type name               Price           Sold/capacity 
rtype1                               0.00$              20/20
rtype2                               5.00$              5/10

我不了解如何正确实现这一目标。现在,我有这个查询来获取每种注册类型和每种注册类型的计数:

$participantsOfEachType = Participant::
 select(DB::raw('registration_type_id, count(registration_type_id)'))
->groupBy('registration_type_id')->get();

此查询返回以下结果。但是没有考虑召开特定的会议。您知道要考虑特定会议ID的必要条件,以便可以在上面的表格示例中的表格中显示结果吗?

Collection {#271 ▼
  #items: array:2 [▼
    0 => Participant {#282 ▼
    ...
      #attributes: array:2 [▼
        "registration_type_id" => 1
        "count(registration_type_id)" => 2
      ]
    ...
    }
    1 => Participant {#279 ▼
    ...
      #attributes: array:2 [▼
        "registration_type_id" => 2
        "count(registration_type_id)" => 2
      ]
      ... 
    }
  ]
}

该问题的相关模型:

用户模型:

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

注册模型:

// user that did the registration
public function customer(){
    return $this->belongsTo(User::class, 'user_that_did_registration', 'id');
}
 public function participants(){
    return $this->hasMany('App\Participant');
}

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

会议模型:

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

参与者模式:

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

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

2 个答案:

答案 0 :(得分:1)

尝试
select conference_id, group_concat(concat_ws(':', registration_type_id, cnt)) from (select conference_id, registration_type_id, count(*) as cnt from t group by conference_id, registration_type_id ) tm group by conference_id order by conference_id;

答案 1 :(得分:0)

我假设您的RegistrationType模型具有以下映射

Class RegistrationType Extends Model{

    public function participants(){
        $this->hasMany('App\Participants','registration_type_id')
    }

}

然后对于您的预期输出,您可以获取数据

$conference_id = 1;

$registrationTypes = RegistrationType::withCount('participants')
                                    ->whereHas('participants.registration.conference',function($query) use ($conference_id){
                                        $query->where('id','=', $conference_id)
                                    });
                                    ->get();

当您遍历结果时,$registrationTypes中的每一行将具有属性participants_count,该属性将为您提供该注册类型的参与者数。

See Counting Related Models & Querying Relationship Existence sections