Пример #1
0
 public function delete()
 {
     $id = Input::get('id');
     $validator = Validator::make(array('id' => $id), array('id' => 'required|integer'));
     if ($validator->fails()) {
         return $this->responseJson(false, $validator->messages(), 101);
     }
     $tag = Tag::find($id);
     if (!$tag) {
         return $this->responseJson(false, "不存在该标签!", 102);
     }
     $tag->delete();
     ArticleAttribute::where('attribute_key', 'tag_id')->where('attribute_value', $id)->delete();
     return $this->responseJson(true, "成功删除标签!", 200);
 }
Пример #2
0
 protected function saveTags($id, $tags)
 {
     //获取标签数组,去重复
     $arrTags = array_unique(explode(' ', $tags));
     if (count($arrTags)) {
         /*储存新的标签名*/
         //取出所有标签名
         $allTags = Tag::lists('name')->toArray();
         //比较获得新标签名
         $newTags = array_diff($arrTags, $allTags);
         //若有新标签则添加
         if (count($newTags)) {
             $arrInsert = array();
             foreach ($newTags as $tag) {
                 $arrInsert[] = array('name' => $tag, 'created_at' => date('Y-m-d h:i:s', time()), 'updated_at' => date('Y-m-d h:i:s', time()));
             }
             Tag::insert($arrInsert);
         }
         /*建立文章与标签的关系*/
         //取出标签的id
         $tagIds = Tag::whereIn('name', $arrTags)->lists('id')->toArray();
         //取出已存在的关系
         $allAttrTagIds = ArticleAttribute::where('article_id', $id)->where('attribute_key', 'tag_id')->lists('attribute_value')->toArray();
         //新增关系
         $newAttrTagIds = array_diff($tagIds, $allAttrTagIds);
         if (count($newAttrTagIds)) {
             $arrInsert = array();
             foreach ($newAttrTagIds as $newAttrTagId) {
                 $arrInsert[] = array('article_id' => $id, 'attribute_key' => 'tag_id', 'attribute_value' => $newAttrTagId, 'created_at' => date('Y-m-d H:i:s', time()), 'updated_at' => date('Y-m-d H:i:s', time()));
             }
             ArticleAttribute::insert($arrInsert);
             Tag::whereIn('id', $newAttrTagIds)->increment('use_number');
         }
         //删除关系
         $delAttrTagIds = array_diff($allAttrTagIds, $tagIds);
         if (count($delAttrTagIds)) {
             ArticleAttribute::where('article_id', $id)->where('attribute_key', 'tag_id')->whereIn('attribute_value', $delAttrTagIds)->delete();
             Tag::whereIn('id', $delAttrTagIds)->decrement('use_number');
         }
     }
 }