多表操作

拥有blog表、blog_category表(关联表)、 category表
目的:
(1)在blog对应的页面可以展示与category相关的字段
(2)在blog对应的页面中修改后,直接能影响到blog_category关联表


1、实现的基本思路
(1)在blog模型层引入$category
(2)在category模型层给出一个方法,你起码得让blog获得到数据

 public static function dropDownList(){
        $query=static::find();
        $enums=$query->all();
        return $enums?ArrayHelper::map($enums,'id','name'):[];
    }

(3)在backend\views_form.php增加对于category的操作,比如复选操作

<?= $form->field($model, 'category')->label('栏目')->checkboxList(Category::dropDownList()) ?>

2、实现的基本思路(事务操作)
(1)主要修改控制器中的action方法如:actionCreate

 public function actionCreate()
    {
        $model = new Blog();

        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            $transaction=Yii::$app->db->beginTransaction();
            try{
                $model->save(false);
            $blogId=$model->id;
            $data=[];
            //注意这里的属组形式[blog_id, category_id],一定要跟下面batchInsert方法的第二个参数保持一致
            foreach ($model->category as $k=>$v){
                $data[]=[$blogId,$v];
            }

            //获取属性和表名
            $blogCategory=new BlogCategory();
            $attributes=array_keys($blogCategory->getAttributes());
            $tableName=$blogCategory::tableName();
            //批量插入数据库
            Yii::$app->db->createCommand()->batchInsert(
                $tableName,
                $attributes,
                $data
            )->execute();
            //提交
            $transaction->commit();
            return $this->redirect(['index']);
            }


        catch (Exception $e){
            //回滚
            $transaction->rollback();
            throw $e;
            }
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

这样的话,直接在blog页面进行添加操作,同样也可以save到blog-category表中
(2)可能在blog页面中需要调用blog-category的数据
a、现在blog-category的模型层写个给数据的方法
public static function getRelationCategoryId(blogId){res=static::find()->select('category_id')->where(['blog_id'=> blogId])>all();return res ? ArrayHelper::getColumn($res,’category_id’):[];
}
b、(你把数据怎么获得都给我了,我就不客气了)直接在blog控制器中调用该方法,在render()之前添加

$model->category=BlogCategory::getRelationCategoryId($id);
            return $this->render('update', [ 
                'model' => $model,
            ]);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值