db->beginTransaction(); $arr = []; foreach ($input as $key=>$val) { $r = \common\models\News::find()->andWhere(['subject'=>$val['subject']])->exists(); if($r) { throw new \Exception('资讯:'.$val['subject'].' 已存在'); } $arr[$key]['subject'] = $val['subject']; $arr[$key]['thumb'] = $this->PullImg($val['thumb']); $arr[$key]['abstract'] = $val['abstract']; $arr[$key]['author'] = $val['author']; $arr[$key]['source'] = "诚找房"; $arr[$key]['sort'] = $val['sort']; $arr[$key]['clicks'] = $val['clicks']; $arr[$key]['state'] = $val['state']; if(isset($val['city_name'])) { $arr[$key]['city'] = $this->CityColumn($val['city_name']); } $arr[$key]['category'] = $this->NewsColumn($val['news_name']); $arr[$key]['create_at'] = $_SERVER['REQUEST_TIME']; $arr[$key]['update_at'] = $_SERVER['REQUEST_TIME']; $arr[$key]['content'] = $val['content']; $arr[$key]['del'] = $val['del']; $arr[$key]['open_time'] = $val['open_time']; $arr[$key]['thumb_size'] = $val['thumb_size']; $arr[$key]['short_subject'] = $val['short_subject']; $arr[$key]['true_click'] = $val['true_click']; } if(!empty($arr)) { $column = []; foreach ($arr[0] as $key=>$val) { array_push($column,$key); } $row = Yii::$app->db->createCommand()->batchInsert('pfg_news',$column,$arr)->execute(); if($row >0) { $Transaction->commit(); return true; } } $Transaction->rollBack(); } throw new \Exception('添加失败'); } /* * 转换资讯栏目 */ private function NewsColumn($name) { $model = \common\models\CategoryNews::find()->andWhere(['news_name'=>$name])->one(); if($model) { return $model['id']; } throw new \Exception('未检测到资讯栏目:'.$name); } /* * 转换区域ID */ public function CityColumn($city) { if(!empty($city)) { $row = \common\models\CategoryCity::find()->andWhere(['city_name'=>$city])->one(); if($row) { return $row['id']; } throw new \Exception('未检测到区域:'.$city); } } /* * 拉取图片 */ private function PullImg($img) { if(is_array($img) && !empty($img)) { foreach ($img as $val) { $curl = new curl\Curl(); $resultImg = $curl->get('http://img.yigouf.com/pc/news/'.$val); $imgUrl = Yii::$app->params['img_url']['news']; if(is_file($imgUrl.$val)) { unlink($imgUrl.$val); } if(!file_put_contents($imgUrl.$val,$resultImg)) { throw new \Exception('图片添加失败,请联系管理员'); } } return json_encode(array_values($img)); } } }