我在if/else
中有一个Yii Framework
条件。当用户是admin时,数据库查询不应该有过滤器,如果用户不是admin,则数据库查询应该有过滤器。
if($ut=='Admin'){ // if the user is Admin the query should not have a filter
$queryCustomer = Yii::app()->db->createCommand()
->select('cust.mobile_number as customer,sum(trans.price) as sales,trans.datetime')
->from('customers cust')
->join('transactions trans', 'cust.id=trans.customer_id')
->where('transaction_type_id=:id', array(':id'=>1))
->group('customer_id')
->order('trans.datetime DESC')
->queryAll();
$per_customer=$this->renderTableCustomer($queryCustomer);
} else { // if the user is not Admin the query should have a filter
$queryCustomer = Yii::app()->db->createCommand()
->select('cust.mobile_number as customer,sum(trans.price) as sales,trans.datetime')
->from('customers cust')
->join('transactions trans', 'cust.id=trans.customer_id')
->where('transaction_type_id=:id', array(':id'=>1))
->andWhere('user_id=:userID',array(':userID'=>$filter))
->group('customer_id')
->order('trans.datetime DESC')
->queryAll();
$per_customer=$this->renderTableCustomer($queryCustomer);
除了我在else查询中添加了where语句之外,查询是相同的。由于查询是相同的,是否有可能将它放在函数上,当我调用它时,我会将where语句添加为参数?
答案 0 :(得分:0)
你真的不需要一个功能。你可以这样做:
$queryCustomer = Yii::app()->db->createCommand()
->select('cust.mobile_number as customer,sum(trans.price) as sales,trans.datetime')
->from('customers cust')
->join('transactions trans', 'cust.id=trans.customer_id')
->where('transaction_type_id=:id', array(':id'=>1))
if($ut !== 'Admin') // if the user is Admin the query should not have a filter
->andWhere('user_id=:userID',array(':userID'=>$filter))
->group('customer_id')
->order('trans.datetime DESC')
->queryAll();
$per_customer=$this->renderTableCustomer($queryCustomer);

这样,如果用户不是Admin,那么->addWhere()
方法将不会执行。所以函数是针,所以作为单个方法调用的双查询...
希望这有帮助! :d