<?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(){

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

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

        return $catgList;
    }

    /**
     * 查询所有媒资列表(分页)
     * @param $request
     * @return mixed
     * @throws DatabaseException
     */
    public static function catgListPage($request){
        try{
            $catgList = MediaCategoryModel::paginate(10);

        }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;
    }
}
