/**
* 添加标签方法
* param:$event为存储传入的tag数组值
*/
public function _eventAddTag($event)
{
//实例化表单模型
$tag = new TagForm();
//传值
$tag->tags = $event->data['tags'];
//实现保存方法
$tagids = $tag->saveTags();
//删除原先的关联关系,与文章多对多的关系,利用数据库表中的relation_post_tags的对应关系
RelationPostTags::deleteAll(['post_id' => $event->data['id']]);
//遍历多维数据
if (!empty($tagids)) {
foreach ($tagids as $k=>$id){
$row[$k]['post_id'] = $this->id;
$row[$k]['tag_id'] = $id;
}
//实现批量插入保存
$res = (new Query())->createCommand()
->batchInsert(RelationPostTags::tableName(),['post_id','tag_id'],$row)
->execute();
//保存失败
if ($res)
throw new \Exception("关联保存失败");
}
}
<?php
namespace frontend\models;
use Yii;
use common\models\Tags;
use yii\base\Model;
/**
* 标签表单模型
* @author ZJJ
*
*/
class TagForm extends Model
{
//定义参数属性
public $id;
public $tags;
/**
* 加入规则
*/
public function rules()
{
return [
['tags','required'],
['tags','each','rule'=>['string']],
];
}
/**
* 保存标签集合
* 返回所有的id
*/
public function saveTags()
{
//定义常量ids
$ids = [];
if (!empty($this->tags)) {
foreach ($this->tags as $tag){
$ids[] = $this->_saveTag($tag);
}
}
return $ids;
}
/**
* 保存单个标签的方法
*/
private function _saveTag($tag)
{
//利用业务逻辑
$model = new Tags();
//查询标签是否存在
$res = $model->find()->where(['tag_name'=>$tag])->one();
//新建标签
if (!$res) {
//数据保存,与数据表中tags字段保持一致
$model->tag_name = $tag;
$model->post_num = 1;
if (!$model->save()){
throw new \Exception("保存标签失败");
}
return $model->id;
}else {
//post_num字段的值基础上+1
$res->updateCounters(['post_num' => 1]);
}
return $res->id;
}
}
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['index', 'create', 'upload', 'ueditor'],
'rules' => [
[
'actions' => ['index'],
'allow' => true,
],
[
'actions' => ['create', 'upload', 'ueditor'],
'allow' => true,
'roles' => ['@'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'*' => ['get', 'post'],
'create' => ['get','post'],
],
],
];
}