如何在多列搜索警予使用$criteria->compare()
或$criteria->addCondition()
上我有一個表命名產品,並在這張表內部我有多個列,例如:「productId,name,description ...」 我需要我的用戶能夠搜索多個列,如 $criteria->compare('name' AND 'id' And '','' ,$search,true);
但這絕對不行!只有一列工作如下: $ criteria-> addCondition(「name LIKE'%$ search%'」); 或$ criteria-> compare('productId',$ search,true);
我的搜索形式:
<div class="search-bar col-md-9 col-lg-9 no-hor-padding">
\t <form role="form" onSubmit="return dosearch();" class="navbar-form- navbar-left- search-form" style="padding-left: 0;"
\t \t action="<?php echo Yii::app()->createAbsoluteUrl('/'); ?>" method="get">
\t \t <input type="text" maxlength="30" placeholder="<?php echo Yii::t('app','Search products'); ?>" class="search-icon form-control input-search <?php echo !empty(Yii::app()->user->id) ? "" : "sign" ?>" name="search"></input>
\t </form> \t \t
</div>
我的功能或控制器:
if(!empty($search)) {
//$criteria->addCondition("name LIKE '%$search%'");
$criteria->compare('name',$search,true);
$searchCriteria = clone $criteria;
$searchproducts = Products::model()->find($searchCriteria);
if(empty($searchproducts)){
$catrest = 1;
$location = 1;
}
}
產品::模型()是指產品表 下面是搜索功能表格「hts_products」的模型類。:
public function search()
\t {
\t \t // @todo Please modify the following code to remove attributes that should not be searched.
\t \t $criteria=new CDbCriteria;
\t \t $criteria->compare('productId',$this->productId);
\t \t $criteria->compare('userId',$this->userId);
\t \t $criteria->compare('name',$this->name,true);
\t \t $criteria->compare('price',$this->price);
\t \t $criteria->compare('quantity',$this->quantity);
\t \t $criteria->compare('sizeOptions',$this->sizeOptions,true);
\t \t $criteria->compare('productCondition',$this->productCondition,true);
\t \t $criteria->compare("from_unixtime(`createdDate`, '%d-%m-%Y')",$this->createdDate,true);
\t \t //if(!empty($this->createdDate))
\t \t //$criteria->condition = "from_unixtime(`createdDate`, '%d-%m-%Y') = '$this->createdDate'";
\t \t //else
\t \t //$criteria->compare('createdDate',$this->createdDate);
\t \t /* $criteria->compare('likeCount',$this->likeCount);
\t \t $criteria->compare('commentCount',$this->commentCount); */
\t \t $criteria->compare('chatAndBuy',$this->chatAndBuy);
\t \t $criteria->compare('exchangeToBuy',$this->exchangeToBuy);
\t \t $criteria->compare('instantBuy',$this->instantBuy);
\t \t $criteria->compare('paypalid',$this->paypalid,true);
\t \t // $criteria->order = 'productId DESC';
\t \t return new CActiveDataProvider($this, array(
\t \t 'criteria'=>$criteria,
\t \t 'pagination'=>array(
'pageSize'=>10,
\t \t),
\t \t 'sort'=>array(
'defaultOrder'=>'productId DESC',
\t \t)
\t \t));
\t }
感謝。
閱讀:http://www.yiiframework.com/doc-2.0/yii-db-queryinterface.html#where()-detail? – TomaszKane
感謝@TomaszKane對你的迴應,但仍不明白.. – zaxf
看起來像yii1代碼不是yii2,你確定這是yii2嗎? :) –