2012-05-16 31 views
0

有沒有辦法動態修改Yii中的關係模型給出的標準是什麼?動態改變關係的條件

例如,我有一個博弈模型這種關係,這將使我都贏得了它

'total_points' => [self::STAT, 'Point', 'game_id', 'select' => 'SUM(earned)'] 

這只是正常的要點。但是,我希望能夠根據動態選擇的特定用戶標識對其進行削減。

我將如何創建這樣,將​​返回在這場比賽中贏得total_points對於一個具體的,不斷變化的用戶,其中USER_ID是點模型的屬性下面的方法?

function getUserPoints($user_id) { 
    return $this->someCriteriaChangingMethod('user_id = $user_id')->total_points; 
} 

回答

4

通過yii guide這應該工作:

$model->total_points(array(
    'condition' => "user_id = :uId", 
    'params' => array(':uId' => $user_id), 
)); 

這是你想要的嗎?

+0

完美。我發誓我已經嘗試過,但我猜不是。也許我會瘋了。 –

0

我不認爲你可以做到這一點。 這是一種替代方法

function getUserPoints($user_id) { 

    $row=Yii::app()->db->createCommand()->select("SUM(earned) as total_points") 
        ->from("point") 
        ->where('user_id = :user_id',array(":user_id"=>$user_id)) 
        ->queryRow(); 
    return $row["total_points"]; 

} 
0

動態修改的關係,你可以使用的方法CActiveRecord->getRelated(),它允許我做這件事

function getUserPoints($user_id) { 
    $t = $this->getRelated('total_points', false, [ 
     'condition' => 'user_id = :user_id', 
     'params' => [':user_id' => $user_id], 
    ]); 

    return $t; 
}