Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 14 additions & 27 deletions src/Entity.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,21 +40,14 @@ public function __construct(?Model $model = null)
$this->initWeakMap();

// 获取实体模型参数
$baseOptions = $this->getBaseOptions();
$options = $this->getOptions();

foreach (['viewMapping', 'autoMapping'] as $item) {
$options[$item] = array_merge($baseOptions[$item] ?? [], $options[$item] ?? []);
}

$options = array_merge($baseOptions, $options);
$options = $this->getOptions();

if (is_null($model)) {
$class = !empty($options['modelClass']) ? $options['modelClass'] : str_replace('\\entity\\', '\\model\\', static::class);
$model = new $class();
$model->entity($this);
}

$model->entity($this);
self::$weakMap[$this] = [
'model' => $model,
];
Expand All @@ -72,17 +65,7 @@ protected function initWeakMap()
}

/**
* 定义实体模型的基础配置参数.
*
* @return array
*/
protected function getBaseOptions(): array
{
return [];
}

/**
* 定义实体模型相关配置参数.
* 在实体模型中定义 返回相关配置参数.
*
* @return array
*/
Expand Down Expand Up @@ -134,12 +117,11 @@ public function getOption(string $name, $default = null)
* 创建新的实例.
*
* @param Model $model 模型连接对象
* @param array $options 查询参数
*/
public function newInstance(?Model $model, array $options = [])
public function newInstance(?Model $model)
{
$entity = new static();
return $entity->setModel($model, $options);
return $entity->setModel($model);
}

/**
Expand Down Expand Up @@ -326,10 +308,15 @@ public function offsetUnset(mixed $name): void
public static function __callStatic($method, $args)
{
$entity = new static();
if (in_array($method, ['destroy', 'create', 'update', 'saveAll'])) {
// 调用model的静态方法
$db = $entity->model();
} else {
$modelClass = get_class($entity->model());

$staticMethods = (new \ReflectionClass($modelClass))->getMethods(\ReflectionMethod::IS_STATIC);
$staticPublicMethods = array_filter($staticMethods, fn($m) => $m->isPublic());

if (in_array($method, array_column($staticPublicMethods, 'name'))) {
// 调用model的静态方法
$db = $modelClass;
} else {
// 调用Query类查询方法
$db = $entity->model()->db();
}
Expand Down
1 change: 1 addition & 0 deletions src/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
use think\contract\Jsonable;
use think\db\BaseQuery as Query;
use think\db\Express;
use think\exception\InvalidArgumentException;
use think\exception\ValidateException;
use think\model\Collection;
use think\model\contract\Modelable;
Expand Down