Yii2 ActiveRecord多表关联和多表关联搜索的实现

需求:假设我们有一张商品表goods和一张商品分类表categories,通过商品分类简称搜索商品列表

goods表AR

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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' => '修改时间'
];
}
}

商品搜索模型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<?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;
}
}
坚持原创技术分享,您的支持将鼓励我继续创作!
0%