在我的 Yii 项目中,我需要按一些自定义值搜索和排序数据。我有'users'
表,我需要每个用户实例都有month_profit
属性,该属性应该结合 SQL 数据 + 大量我自己的计算。目前我在我的用户模型中有:
public $month_profit;
public function search($pageSize = 10, $defaultOrder = '`t`.`reg_date` DESC')
{
$criteria = new CDbCriteria;
$criteria->with = array('money');
$requests_table = Requests::model()->tableName();
$requests_count_sql = "(SELECT COUNT(*) FROM $requests_table rt WHERE rt.partner_id = t.id) ";
$referrals_table = Referrals::model()->tableName();
$referrals_count_sql = "(SELECT COUNT(*) FROM $referrals_table reft WHERE reft.user_id = t.id) ";
$referrals_payed_sql = "(SELECT COUNT(*) FROM $referrals_table reft WHERE reft.user_id = t.id AND reft.status = 'Оплачено') ";
//$month profit_sql = ???;
$criteria->select = array(
'*',
$requests_count_sql . "as requests_count",
$referrals_count_sql . "as referrals_count",
$referrals_payed_sql . "as referrals_payed_count",
$month_profit_sql . "as month_profit",
);
$criteria->compare($requests_count_sql, $this->requests_count);
$criteria->compare($referrals_count_sql, $this->referrals_count);
$criteria->compare($referrals_payed_sql, $this->referrals_payed_count);
$criteria->compare($month_profit_sql, $this->month_profit);
$criteria->compare('t.id', $this->id);
$criteria->compare('t.reg_date', $this->reg_date, true);
$criteria->compare('username', $this->username, true);
$criteria->compare('password', $this->password, true);
$criteria->compare('site', $this->site, true);
$criteria->compare('status', $this->status, true);
return new CActiveDataProvider(get_class($this), array(
'criteria' => $criteria,
'pagination' => array( 'pageSize' => $pageSize ),
'sort' => array(
'defaultOrder' => $defaultOrder,
'attributes' => array(
'id' => array(
'asc' => '`t`.`id` ASC',
'desc' => '`t`.`id` DESC',
),
'email' => array(
'asc' => '`t`.`email` ASC',
'desc' => '`t`.`email` DESC',
),
'requests_count' => array(
'asc' => 'requests_count ASC',
'desc' => 'requests_count DESC',
),
'referrals_count' => array(
'asc' => 'referrals_count ASC',
'desc' => 'referrals_count DESC',
),
'referrals_payed_count' => array(
'asc' => 'referrals_payed_count ASC',
'desc' => 'referrals_payed_count DESC',
),
'money' => array(
'asc' => 'money.profit',
'desc' => 'money.profit DESC',
),
'fullProfit' => array(
'asc' => 'money.full_profit',
'desc' => 'money.full_profit DESC',
),
'*',
),
)
));
}
例如,我的用户模型中有一个关系:
public function relations()
{
return array(
'clients' => array( self::HAS_MANY, 'Referrals', 'user_id'),
假设我的month_profit
将是相等的:clients
过去 30 天中注册的用户数 * 150。我需要以某种方式将此数据传递给search()
并创建 CDbCriteria 以对用户进行排序month_profit
。这是真的吗?:) 我应该创建另一个函数来计算所有内容然后传递给search()
吗?到目前为止,我所有的尝试都失败了。