yii2表关联实例

时间:2021-11-30 15:12:35

yii2表关联

1.两张表关联,以“商品表关联品牌表”为例

控制器中:

$goods_model=new Goods();

$goods_info=$goods_model::find()->joinWith('brand')->all();

yii2表关联实例

商品模型中:

//关联品牌表
    public function getbrand(){
        return $this->hasMany(Brand::className(), ['brand_id' => 'goods_brand_id']);
    }

2.三张表关联,以“商品表关联品牌表和分类表”为例

控制器中:

$goods_model=new Goods();

$goods_info=$goods_model::find()->joinWith('brand','category')->orderBy('goods.goods_id desc');

商品模型中:

//关联品牌表

public function getbrand(){

return $this->hasMany(Brand::className(),['brand_id'=>'goods_brand_id']);

}

//关联类别表

public function getcategory(){

return $this->hasMany(Category::className(),['category_id'=>'goods_category_id']);

}

yii2表关联实例