问题
I have a couple of dropdown filters in my GridView, in the search part of my model I have:
if ($this->agent_primary != "") {
$criteria->addColumnCondition(array('agent_type_id'=>1, 'agent.agent_id'=>$this->agent_primary));
}
if ($this->agent_voice != "") {
$criteria->addColumnCondition(array('agent_type_id'=>2, 'agent.agent_id'=>$this->agent_voice));
}
if ($this->agent_commercial != "") {
$criteria->addColumnCondition(array('agent_type_id'=>3, 'agent.agent_id'=>$this->agent_commercial));
}
I need to somehow combine this so if someone selects two of the three dropdowns (or all three) they get the correct results, currently the sql has there WHERE in separate brackets for each addColumnCondition:
WHERE (condition1a = a AND condition1b = b) AND (condition2a = a AND condition2b = b)
instead of
WHERE (condition1a = a AND condition1b = b) OR (condition2a = a AND condition2b = b)
回答1:
You can simply use the third parameter operator of addColumnCondition, set it as 'OR'
:
if ($this->agent_primary != "") {
$criteria->addColumnCondition(array('agent_type_id'=>1, 'agent.agent_id'=>$this->agent_primary),'AND','OR');
}
And you'll get:
WHERE (agent_type = 1 AND agent.agent_id = X) OR (condition2a = a AND condition2b = b)
回答2:
Use addCondition function add your condition here $criteriaStr; As you need to built your string here and use it in.
$criteriaStr = "";
if ($this->agent_primary != "") {
$criteriaStr .= '(agent_type_id=1 AND agent.agent_id='.$this->agent_primary.')';
}
if ($this->agent_voice != "") {
if($criteriaStr !== '' ) { $criteriaStr .= ' OR '; }
$criteriaStr .= '(agent_type_id=2 AND agent.agent_id='.$this->agent_voice.')';
}
if ($this->agent_commercial != "") {
if($criteriaStr !== '' ) { $criteriaStr .= ' OR '; }
$criteriaStr .= '(agent_type_id=3 AND agent.agent_id='.$this->agent_commercial.')';
}
$criteria->addCondition($criteriaStr);
来源:https://stackoverflow.com/questions/13908460/yii-combining-addcolumncondition-in-cdbcriteria