登录
原创

保存新闻数据到数据库

发布于 2021-06-11 阅读 60
  • 后端
原创
    static public function addNews($data)
    {
        self::startTrans();
        try {
            $s_id = Sort::where('s_name', $data[0]['category'])
                ->value('s_id');
            if (empty($s_id)) {
                $res = Sort::create(['s_name' => $data[0]['category']]);
                $s_id = $res->s_id;
            }
            foreach ($data as $k => $v) {
                $flag=self::repeat($v['uniquekey'] ?? '');
                if ($flag==0) {
                    self::create([
                        'uniquekey' => $v['uniquekey'],
                        'title' => $v['title'],
                        's_id' => $s_id,
                        'author_name' => $v['author_name'],
                        'url' => $v['url'],
                        'thumbnail_pic_s' => $v['thumbnail_pic_s'] ?: '',
                        'thumbnail_pic_s02' => $v['thumbnail_pic_s02'] ?? '',
                        'thumbnail_pic_s03' => $v['thumbnail_pic_s03'] ?? '',
                        'is_content' => $v['is_content']
                    ]);
                }
            }
            self::commit();
            return;
        }catch (\Exception $e){
            self::rollback();
            throw  $e;
        }
    }
    static public function repeat($uniquekey=null)
    {
        $res=self::where('uniquekey',$uniquekey)
            ->field('id')
            ->find();
        $flag=0;
        if (!empty($res)){
            $flag=1;
        }
        return $flag;
    }

    public function mewsAdd()
    {
        $param = input();
        $type = '类型';
        $page = 当前页;
        $page_size = 每页条数;
        $is_filter = 是否有返回数;
        if (isset($param['type']) && !empty($param['type'])) {
            $type = $param['type'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $type = $param['page'];
        }
        if (isset($param['page_size']) && !empty($param['page_size'])) {
            $type = $param['page_size'];
        }
        if (isset($param['is_filter']) && !empty($param['is_filter'])) {
            $type = $param['is_filter'];
        }

        $appkey = "新闻数据key值";
        $url = "http://v.juhe.cn/toutiao/index?" . "type=" . $type . "&page=" . $page . "&page_size=" . $page_size . "&is_filter=" . $is_filter . "&key={$appkey}";
        $res = file_get_contents($url);
        $data = json_decode($res, true);
        if ($data['error_code'] != 0) {
            返回请求结果;
        }
        $newsData = $data['result']['data'];
        NewsModel::addNews($newsData);
        跳转;
    }

评论区

励志做一条安静的咸鱼,从此走上人生巅峰。

0

0

0

举报