2015-10-20 44 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){ ... 
相關問題