Township.php 3.0 KB
<?php
/**
+-----------------------------------------------------------------------------------------------------------------------
 * 模型层:地区-乡镇 模型类
+-----------------------------------------------------------------------------------------------------------------------
 *
 * PHP version 7
 *
 * @category  App\Models\Area
 * @package   App\Models\Area
 * @author    Richer <yangzi1028@163.com>
 * @date      2021年11月3日17:04:04
 * @copyright 2020-2022 Richer (http://www.Richer.com/)
 * @license   http://www.Richer.com/ License
 * @link      http://www.Richer.com/
 */
namespace App\Models\Area;

use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Facades\DB;

/**
 * Class Township
 *
 * @category  App\Models\Area
 * @package   App\Models\Area
 * @author    Richer <yangzi1028@163.com>
 * @date      2021年11月3日17:04:04
 * @copyright 2020-2022 Richer (http://www.Richer.com/)
 * @license   http://www.Richer.com/ License
 * @link      http://www.Richer.com/
 */
class Township extends Area
{
    // 指定数据库表
    const TABLE = 'area_townships';
    protected $table = self::TABLE;

    // 指定对象显示名称:方便系统统一查询和做其他处理
    const OBJ_NAME      = 'township';
    const OBJ_NAME_ZH   = '乡镇';

    // 级别
    const LEVEL = 4;

    /**
     * @return HasMany
     */
    public function villages(): HasMany
    {
        return $this->hasMany(Village::class);
    }

    /**
     * @return HasMany
     */
    public function groups(): HasMany
    {
        return $this->hasMany(Group::class);
    }

    /**
     * @return BelongsTo
     */
    public function province(): BelongsTo
    {
        return $this->belongsTo(Province::class);
    }

    /**
     * @return BelongsTo
     */
    public function city(): BelongsTo
    {
        return $this->belongsTo(City::class);
    }

    /**
     * @return BelongsTo
     */
    public function county(): BelongsTo
    {
        return $this->belongsTo(County::class);
    }

    /**
     * @return BelongsTo
     */
    public function township(): BelongsTo
    {
        return $this->belongsTo(Township::class);
    }

    /**
     * 根据区域的code获取区域的的代码集:主要为laravel-admin select组件使用
     *
     * @param int $pid
     * @param string $operate
     * @return array
     */
    public static function getSelectOptions($pid = 0, $operate = '')
    {
        if (!$pid) {
            return [];
        }

        if ($operate === 'link') {
            return self::where('county_id', $pid)->orderBy('name')->get(['id', DB::raw('name as text')]);
        }

        if ($pid) {
            $list = self::where('county_id', $pid)->get(['id','name']);
        } else {
            $list = self::all(['id','name']);
        }
        $options = [];
        foreach ($list as $vo) {
            $options[$vo->id] = $vo->name;
        }
        return $options;
    }
}