需求:假设我们有一张商品表goods和一张商品分类表categories,通过商品分类简称搜索商品列表
goods表AR
namespace common\models;
use Yii;
use yii\db\ActiveRecord;
class Goods extends ActiveRecord
{
/**
* {@inheritdoc}
*/
public static function tableName()
{
return '{{%goods}}';
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => '商品ID',
'title' => '商品标题',
'cid' => '商品分类ID',
'created_at' => '添加时间',
'updated_at' => '修改时间'
];
}
/**
* 与商品分类表关联
*/
public function getCategory()
{
return $this->hasOne(Category::className(), ['id'=>'cid']);
}
}
categories表AR
namespace common\models;
use Yii;
use yii\db\ActiveRecord;
class Category extends ActiveRecord
{
/**
* {@inheritdoc}
*/
public static function tableName()
{
return '{{%categories}}';
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => '商品分类ID',
'title' => '商品分类标题',
'short_title' => '商品分类简称',
'created_at' => '添加时间',
'updated_at' => '修改时间'
];
}
}
商品搜索模型
<?php
namespace common\models\search;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\Goods;
class GoodsSearch extends Model
{
public $title;// 商品标题
public $short_title;// 商品分类简称
//检索规则
public function rules()
{
return [
[['title', 'short_title'], 'string'],
];
}
//搜索函数
public function search($params)
{
$query = Goods::find()->joinWith(['category']);
if ($this->load($params) && $this->validate()) {
if(!empty($this->title)) $query->andFilterWhere(['goods.title' => $this->title]);
if(!empty($this->short_title)) $query->andFilterWhere(['category.short_title' => $this->status]);
}
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort' => [
'defaultOrder' => [
'id' => SORT_DESC,
]
],
'pagination' => [
'pageSize' => 15,
],
]);
return $dataProvider;
}
}