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

115 lines
2.7 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace app\common\model\food;
use think\Model;
use think\db\Query;
use think\facade\Session;
use think\facade\Request;
use think\facade\Cache;
/**
* 模型基类
*/
class BaseModel extends Model
{
// 当前访问的小程序ID
public static $applet_id;
// 定义表名
protected $name;
// 模型别名
protected $alias = '';
// 定义全局的查询范围
protected $globalScope = ['applet_id'];
//是否允许全局查询applet_id
protected $isGlobalScopeAppletId = true;
// 错误信息
protected $error = '';
/**
* 模型基类初始化
*/
public static function init()
{
parent::init();
self::getAppletId();// 绑定applet_id
}
/**
* 获取当前操作的小程序ID
* @return int|null
*/
private static function getAppletId()
{
$app_name = app_name();
if (empty(self::$applet_id) && in_array($app_name, ['store', 'api'])) {
if ($app_name == 'store') {
$url = explode('.',substr(Request::url(),7));
$session = Session::get('hema_store_' . $url[0]);
isset($session['applet']['applet_id']) && self::$applet_id = $session['applet']['applet_id'];
}else{
self::$applet_id = (int)request()->param('applet_id');
}
}
return self::$applet_id;
}
/**
* 定义全局的查询范围
* @param Query $query
* @return bool
*/
public function scopeApplet_id(Query $query)
{
if (!$this->isGlobalScopeAppletId) return false;
$applet_id = self::getAppletId();
$applet_id > 0 && $query->where($query->getTable() . '.applet_id', $applet_id);
return true;
}
/**
* 查找单条记录
* @param $data
* @param array $with
* @return array|static|null
*/
public static function get($data, $with = [])
{
try {
$query = (new static)->with($with);
return is_array($data) ? $query->where($data)->find() : $query->find((int)$data);
} catch (\Exception $e) {
return false;
}
}
/**
* 获取当前调用来源的应用名称
* 例如admin, api, store, task
* @return string|bool
*/
protected static function getCalledModule()
{
if (preg_match('/app\\\(\w+)/', get_called_class(), $class)) {
return $class[1];
}
return 'common';
}
/**
* 返回错误信息
* @return string
*/
public function getError()
{
return empty($this->error) ? false : $this->error;
}
}