<?php
/**
* Created by PhpStorm.
* User: 33598
* Date: 2019/2/2
* Time: 10:54
*/
namespace frontend\models;
use common\models\Tags;
use yii\base\Model;
/*
* 标签的表单模型
*/
class TagForm extends Model
{
public $id;
public $tags;
public function rules()
{
return [
['tags','required'],
['tags', 'each', 'rule' => 'string']
];
}
/*
* 保存标签集合
*/
public function saveTags(){
$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){
$model -> tag_name = $tag;
$model -> post_num = 1;
if(!$model -> save()){
throw new \Exception("保存标签失败!");
}
return $model -> id;
}else{
$res -> updateCounters(['post_num' => 1]);
}
return $res -> id;
}
}
<?php
namespace frontend\models;
/**
* Created by PhpStorm.
* User: Mr.L
* Date: 2018/5/22
* Time: 16:20
* 文章表单模型
*/
use common\models\RelationPostTags;
use yii\base\Model;
use Yii;
use common\models\Posts;
use Yii\db\Query;
class PostForm extends Model{
public $id;
public $title;
public $content;
public $label_img;
public $cat_id;
public $tags;
public $_lastError = "";
/*
* 定义场景
* SCENAROIS_CREATE 创建
* SCENAROIS_UPDATE 更新
* */
const SCENAROIS_CREATE = 'create';
const SCENAROIS_UPDATE = 'update';
/*
* 定义事件
* EVENT_AFTER_CREATE 创建之后的事件
* EVENT_AFTER_UPDATE 更新之后的事件
*/
const EVENT_AFTER_CREATE = 'eventAfterCreate';
const EVENT_AFTER_UPDATE = 'eventAfterUpdate';
/**
* 场景设置
* @return array|void
*/
public function scenarios(){
$scenarios = [
self::SCENAROIS_CREATE =>['title', 'content', 'label_img', 'cat_id', 'tag'],
self::SCENAROIS_UPDATE =>['title', 'content', 'label_img', 'cat_id', 'tag'],
];
return array_merge(parent::scenarios(), $scenarios);
}
public function rules(){
return [
[['id', 'title', 'content','cat_id'],'required' ],
[['id', 'cat_id'],'integer'],
//[['title ','string', 'min' => 4, 'max' => 50]],//设置最小最大值
['title','string','min'=>4,'max'=>50]
];
}
public function attributeLabels(){
return[
'id' => '编码',
'title' => '标题',
'content' => '内容',
'label_img' => '标签图',
'tags' => '标签',
'cat_id' => '分类',
];
}
/**
* 文章创建
* @return bool
* @throws \yii\db\Exception
*/
public function create(){
//事务
$transaction = Yii::$app->db->beginTransaction();
try{
$model = new Posts();
$model -> setAttributes($this->attributes);
$model -> summary = $this-> _getSummary();
$model -> user_id = Yii::$app->user->identity->id;
$model -> user_name = Yii::$app->user->identity->username;
$model -> is_valid = Posts::IS_VALID;
$model -> created_at = time();
$model -> updated_at = time();
$model -> is_valid = Posts::IS_VALID;
if (! $model -> save()){
throw new \Exception("文章保存失败");
}
$this->id = $model->id;
//调用事件
$data = array_merge($this->getAttributes(), $model->getAttributes());
$this-> _evenAfterCreate($data);
$transaction ->commit();
return true;
}catch (\Exception $e){
$transaction -> rollBack();
$this -> _lastError = $e -> getMessage();
return false;
}
}
/**
* 截取文章摘要
* @param int $s
* @param int $e
* @param string $char
* @return null|string
*/
private function _getSummary($s = 0, $e = 90, $char = 'utf-8'){
if(empty($this->content)){
return null;
}
return (mb_substr(str_replace(' ',"",strip_tags($this->content)), $s, $e,$char ));
}
/*
* 创建完成后调用的事件方法
* */
public function _evenAfterCreate($data){
//添加事件
$this->on(self::EVENT_AFTER_CREATE, [$this,'_eventAddTag'], $data);
//触发事件
$this->trigger(self::EVENT_AFTER_CREATE);
}
public function _eventAddTag($event){
//保存标签
$tag = new TagForm();
$tag->tags = $event->data['tags'];
$tagIds = $tag->saveTags();
//删除原先关联关系
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('关联关系保存失败!');
}
}
}
}