BlogCategoryLogic.php 2.3 KB
<?php

namespace App\Http\Logic\Bside\Blog;

use App\Enums\Common\Code;
use App\Http\Logic\Bside\BaseLogic;
use App\Models\Blog\BlogCategory as BlogCategoryModel;
use App\Models\Blog\Blog as BlogModel;
use Illuminate\Support\Facades\DB;

class BlogCategoryLogic extends BaseLogic
{
    public function __construct()
    {
        parent::__construct();

        $this->model = new BlogCategoryModel();
    }

    /**
     * @name :添加时验证上级分类是否有商品,有则替换带当前分类下
     * @return void
     * @author :liyuhang
     * @method
     */
    public function add_blog_category(){
        DB::beginTransaction();
        $this->param = $this->requestAll;
        $this->param['project_id'] = $this->user['project_id'];
        $this->param['operator_id'] = $this->user['id'];
        $this->param['create_id'] = $this->user['id'];
        $this->param['created_at'] = date('Y-m-d H:i:s');
        $this->param['updated_at'] = date('Y-m-d H:i:s');
        $cate_id = $this->model->insertGetId($this->param);
        if($cate_id === false){
            DB::rollBack();
            $this->fail('error',Code::USER_ERROR);
        }
        //判断为子分类时
        if(isset($this->param['pid']) && !empty($this->param['pid'])) {
            //查看当前上级分类下是否有其他分类
            $cate_info = $this->model->read(['pid' => $this->param['pid'], 'id' => ['!=', $cate_id]]);
            if ($cate_info === false) {
                //查看当前上一级分类下是否有新闻
                $blogModel = new BlogModel();
                $news_info = $blogModel->read(['category_id' => ['like', ',' . $this->param['pid'] . ',']]);
                if ($news_info !== false) {
                    $replacement = ',' . $cate_id . ',';
                    $old = ',' . $this->param['pid'] . ',';
                    //更新所有商品到当前分类
                    $rs = DB::table('gl_Blog')->where('category_id', 'like', '%' . $old . '%')
                        ->update(['category_id' => DB::raw("REPLACE(category_id, '$old', '$replacement')")]);
                    if ($rs === false) {
                        DB::rollBack();
                        $this->fail('error', Code::USER_ERROR);
                    }
                }
            }
        }
        DB::commit();
        return $this->success();
    }
}