多表操作

来源:互联网 发布:腾讯游戏数据分析 编辑:程序博客网 时间:2024/06/08 09:35

拥有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();returnres ? ArrayHelper::getColumn($res,’category_id’):[];
}
b、(你把数据怎么获得都给我了,我就不客气了)直接在blog控制器中调用该方法,在render()之前添加

$model->category=BlogCategory::getRelationCategoryId($id);            return $this->render('update', [                 'model' => $model,            ]);