假设我有具有Category属性的Product model,并且我想使用search()函数拉出所有类别为null的产品。
$productSearch = clone Product::model();
$productSearch->Category = null;
$products = $productSearch->search()->getData();
通过检查生成的SQL我发现它不起作用,查询中根本没有提到类别。最好的方法是什么?
此外,如何搜索某些属性设置为 NULL或某些值
的记录答案 0 :(得分:5)
第一个变种:
// use search scenario, not clone model with metadata
$productSearch = new Product('search');
$productSearch->unsetAttributes();
// get CActiveDataProvider
$dataProvider = $productSearch->search();
// Add null condition
$dataProvider->criteria->addCondition('Category is null');
// Get data - first 10 rows
$products = $dataProvider->getData();
第二个变种(优先):
$products = Product::model()->findAll('Category is null');
答案 1 :(得分:0)
为属性分配空值不起作用,因为它没有被Yii记录:属性的初始值为null,Yii不跟踪修改的属性(这有点烦人)。
这里的工作就是像这样使用它:
$productSearch = clone Product::model();
$productSearch->Category = array(null);
$products = $productSearch->search()->getData();
请注意,如果您想要搜索更高级的Category IS NULL OR Category IN (1, 2, 3)
预期的方法:
$productSearch->Category = array(null, 1, 2, 3);
将无效,因为Yii盲目地将其全部放入单个IN语句中:
Category IN (NULL, 1, 2, 3)
这里的解决方法更复杂,因为它需要在模型搜索方法中使用额外的代码:
public function search()
{
$criteria = new CDbCriteria;
// Work around of inability of Yii to handle IS NULL OR IN () conditions
if (is_array($this->Category) && count($this->Category) > 1)
{
$hasNull = false;
$values = array();
foreach ($this->Category as $value)
{
if (is_null($value))
{
$hasNull = true;
}
else
{
array_push($values, $value);
}
}
$condition = array();
if ($hasNull) array_push($condition, 'Category IS NULL');
if (count($values)) array_push($condition, "Category IN ('" . implode("', '", $values) . "')");
$criteria->addCondition(implode(' OR ', $condition));
}
else
{
$criteria->compare('Category', $this->Category);
}
// other search criterias ...
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}