我有这样的实体:用户,联系人,活动,触摸。
一个用户有多个联系人。一个联系人具有许多活动。活动是多态的,可能是触摸或其他东西。触摸具有类型(电子邮件/访问/呼叫)。
我需要计算用户有多少联系人,这些联系人的活动与访问类型有关。
因此,无论哪种类型,这都是如何计算具有活动的联系人数量的方法:
$this->model->find($id)->contacts()->whereHas('activities')->count();
但是如何只考虑与类型访问相关的活动呢?
$this->model->find($id)->contacts()->whereHas('activities', function($query) {
$query->whereType('App'EloquentModels'Touch') // And touch must have type = visit
)->count();
更新
好吧,似乎我使用查询构建器获得了一些结果。一个注意事项:活动表对于联系人也是多态的,因为它也可能属于其他实体。应该不会有太大的区别。我想在没有连接的情况下写得很漂亮的是:
'DB::table('users')->join('contacts', 'contacts.user_id', '=', 'users.id')
->join('activities', 'activitable_id', '=', 'contacts.id')
->join('touches', 'touches.id', '=', 'activities.child_id')
->where('activities.activitable_type', '=', 'CRM'EloquentModels'Contact')
->where('activities.child_type', '=', 'CRM'EloquentModels'Touch')
->where('touches.type', '=', 'visit')
->distinct()
->count('contacts.id');
我认为您缺少过滤器部分,如果您获得()查询,那么您将检索一个集合,然后您可以为该集合运行过滤器以仅获取您寻求的内容。
$this->model
->find($id)
->contacts()
->whereHas('activities', function($query) {
$query->whereType('App'EloquentMode'Touch')
->get()
->filter(function($touch){
if($touch->type == 'visit') return $touch;
});
})
->count();