改进软删除trait Model类的base方法改为静态定义 全局多次调用有效

This commit is contained in:
thinkphp
2016-08-06 14:49:28 +08:00
parent 177a2456e8
commit 10aae58d82
2 changed files with 18 additions and 55 deletions

View File

@@ -166,10 +166,6 @@ abstract class Model implements \JsonSerializable, \ArrayAccess
$query->pk($this->pk);
}
// 全局作用域
if (method_exists($this, 'base')) {
call_user_func_array([$this, 'base'], [ & $query]);
}
self::$links[$model] = $query;
}
// 返回当前模型的数据库查询对象
@@ -1290,14 +1286,19 @@ abstract class Model implements \JsonSerializable, \ArrayAccess
public function __call($method, $args)
{
$query = $this->db();
// 全局作用域
if (method_exists($this, 'base')) {
call_user_func_array('static::base', [ & $query]);
}
if (method_exists($this, 'scope' . $method)) {
// 动态调用命名范围
$method = 'scope' . $method;
array_unshift($args, $this->db());
array_unshift($args, $query);
call_user_func_array([$this, $method], $args);
return $this;
} else {
return call_user_func_array([$this->db(), $method], $args);
return call_user_func_array([$query, $method], $args);
}
}
@@ -1308,6 +1309,10 @@ abstract class Model implements \JsonSerializable, \ArrayAccess
self::$links[$model] = (new static())->db();
}
$query = self::$links[$model];
// 全局作用域
if (method_exists($model, 'base')) {
call_user_func_array('static::base', [ & $query]);
}
return call_user_func_array([$query, $method], $params);
}

View File

@@ -4,35 +4,6 @@ namespace traits\model;
trait SoftDelete
{
/**
* 分析查询表达式
* @access public
* @param mixed $data 主键列表或者查询条件(闭包)
* @param string $with 关联预查询
* @param bool $cache 是否缓存
* @return Query
*/
protected static function parseQuery(&$data, $with, $cache)
{
$result = self::with($with)->cache($cache);
if (is_array($data) && key($data) !== 0) {
$result = $result->where($data);
$data = null;
} elseif ($data instanceof \Closure) {
call_user_func_array($data, [ & $result]);
$data = null;
} elseif ($data instanceof Query) {
$result = $data->with($with)->cache($cache);
$data = null;
}
if (static::$deleteTime) {
// 默认不查询软删除数据
$result->where(static::$deleteTime, 0);
}
return $result;
}
/**
* 查询软删除数据
* @access public
@@ -96,29 +67,16 @@ trait SoftDelete
return false;
}
public function __call($method, $args)
/**
* 查询默认不包含软删除数据
* @access protected
* @return void
*/
protected static function base($query)
{
if (method_exists($this, 'scope' . $method)) {
// 动态调用命名范围
$method = 'scope' . $method;
array_unshift($args, $this->db());
call_user_func_array([$this, $method], $args);
return $this;
} else {
$query = $this->db();
if (static::$deleteTime) {
$query->where(static::$deleteTime, 0);
return call_user_func_array([$this->db(), $method], $args);
}
}
public static function __callStatic($method, $params)
{
$model = get_called_class();
if (!isset(self::$links[$model])) {
self::$links[$model] = (new static())->db();
}
$query = self::$links[$model];
$query->where(static::$deleteTime, 0);
return call_user_func_array([$query, $method], $params);
}
}