2015-10-20 94 views
0

我有2个表视图和视图。视频有很多观点。我运行此查询:对cakephp 3中关联的计算字段进行排序

$query = $this->Videos->find('all'); 
$query->select([ 
    'id', 
    'title', 
    'user_id', 
    'purchase_count', 
    'created', 
    'price', 
    'total_price'=>$query->newExpr()->add('price*purchase_count'), 
    'created' 
])->distinct(); 
$query->contain([ 
    'Views'=>function($v)use($from,$to){ 
     return $v->select([ 
      'id', 
      'video_id', 
      'free_views_total'=>$v->func()->sum('free_views'), 
      'subscription_view_total'=>$v->func()->sum('subscription_view') 
     ]) 
     ->where([ 
     'Views.created >='=>$from,'Views.created <='=>$to])->group('video_id'); 
}]); 

$this->paginate=[ 
      'sortWhitelist' => [ 
       'id', 
       'title', 
       'user_id', 
       'Views.free_views_total', 
       'Views.subscription_view_total', 
       'purchase_count', 
       'price', 
       'total_price', 
       'created' 
      ]]; 

此查询工作正常,但我不能够通过free_views_totalsubscription_view_total进行排序。我还在sortWhitelist中添加了这些内容。但它也不起作用。请帮忙。提前致谢。

回答

1

由于hasMany关系,cake不加入表,而是执行许多查询并加入结果集。

有很多事情可以做,

您可以通过浏览

$this->Videos->Views->find() 
->group(['video_id']) 
->contain('Videos') 

,或者您可以使用leftJoinWith而不是包含搜索

$query->leftJoinWith([Views'=>function($v)use($from,$to){ ... 
相关问题