php - 在 Laravel 中过滤多态关系

标签 php laravel eloquent

我有这样的实体:用户、联系人、事件、触摸。

一个用户有多个联系人。一个联系人有很多事件。 Activity 是多态的,可能是触摸或其他东西。触摸具有类型(电子邮件/访问/调用)。

我需要计算一个用户有多少联系人,这些联系人的事件属于访问类型的接触。

所以这是计算有事件的联系人数量的方法,无论是什么类型:

$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');

最佳答案

我认为您缺少过滤器部分,如果您 get() 查询,那么您将检索一个集合,然后您可以对该集合运行过滤器以仅获取您要查找的内容。

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

关于php - 在 Laravel 中过滤多态关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29052803/

相关文章:

laravel - 如何在 Eloquent 模型(Laravel)中的自定义属性中使用关系?

php - 创建具有一定半径的多边形

PHP上传的文件权限不正确

php - WhereNotExists Laravel Eloquent

php - Laravel 5 忽略身份验证特定路由

php - 如何从 laravel 5.1 数据库表的 created_at 属性中选择年份和月份?

php - 将列更新为连接列中的值

php - SQL 帮助 ~ 关系数据库模型 ~ 显示结果

c# - PHP 的 __call() 和 __callStatic() 函数在 C# 中等效

php - 调整大小后的图像未保存