cxhxy/app/common/model/food/Category.php
test_service d3170b4d1c 1
2023-12-01 15:43:29 +08:00

1 line
3.6 KiB
PHP

<?php
namespace app\common\model\food;
use think\facade\Cache;
/**
* 商品分类模型
*/
class Category extends BaseModel
{
// 定义表名
protected $name = 'food_category';
// 定义主键
protected $pk = 'category_id';
protected $append = [];
/**
* 分类图片
*/
public function image()
{
return $this->hasOne('addons\\upload\\model\\UploadFile', 'file_id', 'image_id');
}
/**
* 所有分类
*/
public static function getALL($shop_id)
{
$model = new static;
$category = Cache::get('food_category_' . $model::$applet_id);
if (!isset($category[$shop_id])) {
$data = $model->with(['image'])->order(['sort','category_id' => 'desc'])->where(['shop_id' => $shop_id])->select();
$all = !empty($data) ? $data : [];
$tree = [];
foreach ($all as $first) {
if ($first['parent_id'] != 0) continue;
$twoTree = [];
foreach ($all as $two) {
if ($two['parent_id'] != $first['category_id']) continue;
$threeTree = [];
foreach ($all as $three)
$three['parent_id'] == $two['category_id']
&& $threeTree[$three['category_id']] = $three;
!empty($threeTree) && $two['child'] = $threeTree;
$twoTree[$two['category_id']] = $two;
}
if (!empty($twoTree)) {
array_multisort(array_column($twoTree, 'sort'), SORT_ASC, $twoTree);
$first['child'] = $twoTree;
}
$tree[$first['category_id']] = $first;
}
$category[$shop_id] = compact('all', 'tree');
Cache::set('food_category_' . $model::$applet_id,$category);
}
return $category[$shop_id];
}
/**
* 获取所有分类
*/
public static function getCacheAll($shop_id)
{
return self::getALL($shop_id)['all'];
}
/**
* 获取所有分类(树状结构)
*/
public static function getCacheTree($shop_id)
{
return self::getALL($shop_id)['tree'];
}
/**
* 添加新记录
*/
public function add(array $data,$shop_id)
{
$data['shop_id'] = $shop_id;
$data['applet_id'] = self::$applet_id;
$this->deleteCache($shop_id);
return $this->save($data);
}
/**
* 编辑记录
*/
public function edit(array $data,$shop_id)
{
$this->deleteCache($shop_id);
return $this->save($data) !== false;
}
/**
* 删除分类
*/
public function remove()
{
// 判断是否存在菜品
if ($goodsCount = (new Goods)->where(['category_id'=>$this->category_id])->count()) {
$this->error = '该分类下存在' . $goodsCount . '个商品,不允许删除';
return false;
}
// 判断是否存在子分类
if ((new self)->where(['parent_id' => $this->category_id])->count()) {
$this->error = '该分类下存在子分类,请先删除';
return false;
}
$this->deleteCache($this->shop_id);
return $this->delete();
}
/**
* 删除缓存
*/
private function deleteCache($shop_id)
{
$category = Cache::get('food_category_' . self::$applet_id,[]);
if(isset($category[$shop_id])){
unset($category[$shop_id]);
Cache::set('food_category_' . self::$applet_id, $category);
}
return true;
}
}