当前位置: 移动技术网 > IT编程>开发语言>PHP > TP5制作个人博客文章添加功能的制作记录

TP5制作个人博客文章添加功能的制作记录

2018年02月06日  | 移动技术网IT编程  | 我要评论

小白博客记录之文章添加功能的制作记录(控制器部分)(使用一对一及多对多关联)

样式大概是这样的,把amazeUi的模版和H-ui.admin的开源后台模版拼起来做了个页面,虽然感觉自己把页面做丑了。。。

 

因为TP5对于数据库的操作方式有很多种,自己也是在使用中不断的复习,又不断的摸索,希望能够记录并熟练使用其中的一种方式

前台表单post数据有

title,  cat_id,  tags(标签字符串集合,逗号隔开),

img_path,  thumb_path,

subtitle,    editorValue(内容)

要输入的表有

article,   article_content(关联表),   tag_relation(中间表),    tag

表格的字段

article表

article_content表

tag_relation表

tag表

 

设置了几个方法

    //图片上传处理,接受post的img文件信息,返回数组:存储地址和文件后缀
    protected function uploadImg()
    {
        $file = $this->request->file('img');
        $data['ext'] = strrchr($file->getInfo()['name'], '.');
        if ($file) {
            $fileInfo = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
            if ($fileInfo) {
                $data['img_path'] = DS . "uploads" . DS . $fileInfo->getSaveName();
            } else {
                $this->error($fileInfo->getError());
            }
        }
        return $data;
    }
1     //生成缩略图,输入原图路径和文件后缀,输出缩略图路径
2     protected function createThumb($img_path, $ext)
3     {
4         $thumb_path = dirname($img_path) . DS . md5(microtime()) . $ext;
5         $image = \think\Image::open('.' . $img_path);
6         $image->thumb(364, 227)->save('.' . $thumb_path);
7         return $thumb_path;
8     }

 

 1     //输入文章对象,tags字符串,检测tag表是否存在同名tag
 2     //存在则只中间表新增关系,不存在则新增tag,并中间表新增关系
 3     protected function tagSave($article, $tags)
 4     {
 5         $new_tag = explode(',', $tags);
 6         foreach ($new_tag as $vo) {
 7             $check_tag = Tag::where('name', $vo)->find();
 8             //不存在该Tag
 9             if ($check_tag == null) {
10                 $status = $article->tag()->save(['name'=>$vo]) ? false : true;
11             //存在该Tag
12             } else {
13                 $status = $article->tag()->save($check_tag) ? false : true;
14             }
15             if ($status) {
16                 return $article->tag()->getError();
17             }
18         }
19     }

 

 然后是这个文章添加方法

 1     //文章添加后台处理
 2     public function articleAddExecu()
 3     {
 4         $data = $this->request->param();
 5         //图片上传处理
 6         $file = $this->uploadImg();
 7         $data['img_path'] = $file['img_path'];
 8         //生成缩略图
 9         $data['thumb_path'] = $this->createThumb($file['img_path'], $file['ext']);
10         //用户信息
11         $data['user_id'] = $this->request->session('user_id');13 
14         //存入article
15         $article = new ArticleModel($data);
16         $article->allowField(true)->save();
17         //存入article_content
18         $article->articleContent()->save(['content'=>$data['editorValue']]);
19         //存入tag表
20         $this->tagSave($article, $data['tags']);
21     }

 

 使用关联模型的话,几个表格之间好像就不用自己手工用sql来拼接了,而且整个模型的架构感觉也很清晰。确实很好。

 本人接触框架也不久,做些学习的记录,甚有裨益。

 还有很多不足之处,如果发现什么错误,还希望看到的朋友能够指正,小弟感激不尽。

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网