// +---------------------------------------------------------------------- declare (strict_types=1); namespace app\common\model\store; use cores\BaseModel; use app\common\model\Region as RegionModel; use think\model\relation\HasOne; /** * 商家门店模型 * Class Shop * @package app\common\model\store */ class Shop extends BaseModel { // 定义表名 protected $name = 'store_shop'; // 定义主键 protected $pk = 'shop_id'; /** * 追加字段 * @var array */ protected $append = ['cascader', 'region', 'full_address', 'coordinate']; /** * 关联文章封面图 * @return HasOne */ public function logoImage(): HasOne { $module = self::getCalledModule(); return $this->hasOne("app\\{$module}\\model\\UploadFile", 'file_id', 'logo_image_id') ->bind(['logo_url' => 'preview_url']); } /** * 关联文章封面图 * @return HasOne */ public function wechatImage(): HasOne { $module = self::getCalledModule(); return $this->hasOne("app\\{$module}\\model\\UploadFile", 'file_id', 'wechat_img_id') ->bind(['wechat' => 'preview_url']); } /** * 获取器:省市区id集 * @param $value * @param $data * @return array */ public function getCascaderAttr($value, $data): array { return [$data['province_id'], $data['city_id'], $data['region_id']]; } /** * 获取器:省市区名称集 * @param $value * @param $data * @return array * @throws \think\db\exception\DataNotFoundException * @throws \think\db\exception\DbException * @throws \think\db\exception\ModelNotFoundException */ public function getRegionAttr($value, $data): array { return $this->getRegionNames($data); } /** * 获取器:获取完整地址 * @param $value * @param $data * @return string * @throws \think\db\exception\DataNotFoundException * @throws \think\db\exception\DbException * @throws \think\db\exception\ModelNotFoundException */ public function getFullAddressAttr($value, $data): string { $rgionNames = $this->getRegionNames($data); return "{$rgionNames['province']}{$rgionNames['city']}{$rgionNames['region']}{$data['address']}"; } /** * 获取器:坐标经纬度 * @param $value * @param $data * @return string */ public function getCoordinateAttr($value, $data): string { return "{$data['latitude']},{$data['longitude']}"; } /** * 获取省市区名称 * @param array $data * @return array * @throws \think\db\exception\DataNotFoundException * @throws \think\db\exception\DbException * @throws \think\db\exception\ModelNotFoundException */ private function getRegionNames(array $data): array { static $dataset = []; $id = $data[$this->getPk()]; if (!isset($dataset[$id])) { $dataset[$id] = [ 'province' => RegionModel::getNameById($data['province_id']), 'city' => RegionModel::getNameById($data['city_id']), 'region' => RegionModel::getNameById($data['region_id']), ]; } return $dataset[$id]; } /** * 门店详情 * @param int $shopId 门店ID * @param array $with 关联查询 * @return static|array|null */ public static function detail(int $shopId, array $with = []) { return static::get($shopId, $with); } }