/** * 将文章插入数据库 * @param $title * @param $content * @param $publish_at * @param $tag * @return bool */ public static function insert($title, $content, $publish_at, $tag = '') { //插入标签(搜索的分类) $article = new Article(); $article->title = $title; $article->content = $content; $article->author = 'yang'; $article->status = Article::STATUS_GATHER; $article->publish_at = $publish_at; $res = $article->save(false); if ($tag) { try { $tagModel = Tag::find()->where(['name' => $tag])->one(); if (!$tagModel) { $tagModel = new Tag(); $tagModel->name = $tag; $tagModel->article_count = 0; $tagModel->save(false); } $articleTag = new ArticleTag(); $articleTag->article_id = $article->id; $articleTag->tag_id = $tagModel->id; $articleTag->save(false); } catch (\Exception $e) { echo $e->getMessage() . PHP_EOL; } } return $res ? true : false; }
/** * 新建文章 * @return bool * @throws Exception */ public function saveArticle() { if (!$this->validate()) { return false; } if (!$this->tag) { return $this->save(); } $res = $this->save(); try { $tags = explode(';', $this->tag); foreach ($tags as $v) { if (!$v) { continue; } $tag = Tag::findOne(['name' => $v]); if (!$tag) { $tag = new Tag(); $tag->name = $v; $tag->article_count = 0; $res = $tag->save(); $id = $tag->id; } else { $id = $tag->id; } $article_tag = new ArticleTag(); $article_tag->article_id = $this->id; $article_tag->tag_id = $id; $article_tag->save(); //更前标签的文章数量 $tag->article_count++; $tag->save(false); } } catch (Exception $e) { throw new Exception($e->getMessage()); } return $res; }