<?php

namespace App\Model;

use App\Exceptions\DatabaseException;
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;

class MediaCategoryModel extends Eloquent
{
    protected $collection = "media_category";

    protected $connection = 'mongodb';  //使用mongodb

    protected $primaryKey = '_id';

    public function medias()
    {
        return $this->hasMany('MediaModel');
    }

    /**
     * 查询媒资列表
     * @param $request
     * @return mixed
     * @throws DatabaseException
     */
    public static function catgList($request){

        try{
            $catgList = MediaCategoryModel::get()->toArray();

        }catch (\Exception $exception){
            throw new DatabaseException("类别不存在");
        }

        return $catgList;
    }

    /**
     * 添加媒资类别
     * @param $request
     * @return mixed
     * @throws DatabaseException
     */
    public static function addMediaCatg($request){

        try{
            $data = [
                'name'    => $request->name??"百度",
                'status'    => 0
            ];

            $mediaCatg = MediaCategoryModel::where('name',$request->name)->first();

            if (!empty($mediaCatg)){
                throw new \Exception('媒资类别已经存在');
            }
            $id = MediaCategoryModel::insertGetId($data);
        }catch (\Exception $exception){
            throw new DatabaseException("组织不存在");
        }

        return $id;
    }
}
