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

需求:假设我们有一张商品表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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

PeakXin

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值