【问题标题】:Filter polymorphic relationship in Laravel在 Laravel 中过滤多态关系
【发布时间】:2015-05-17 03:35:03
【问题描述】:

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

一个用户有很多联系人。一个联系人有很多活动。活动是多态的,可能是触摸或其他。触摸有一个类型(电子邮件/访问/电话)。

我需要计算一个用户有多少联系人,他们的活动是访问类型的。

这就是如何计算有活动的联系人的数量,无论是什么类型:

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

【问题讨论】:

    标签: php laravel eloquent


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-17
      • 2020-07-15
      • 2019-04-04
      • 1970-01-01
      相关资源
      最近更新 更多