实现请求缓存1天。

This commit is contained in:
2025-04-18 15:38:58 +08:00
parent 2d3f7d8511
commit 96da83a1ab
209 changed files with 19400 additions and 1657 deletions

View File

@@ -24,6 +24,12 @@ use Traversable;
/**
* 数据集管理类
*
* @template TKey of array-key
* @template-covariant TValue
*
* @implements ArrayAccess<TKey, TValue>
* @implements IteratorAggregate<TKey, TValue>
*/
class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSerializable, Arrayable, Jsonable
{
@@ -33,11 +39,19 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria
*/
protected $items = [];
/**
* 构造函数
* @param iterable<TKey, TValue>|Collection<TKey, TValue> $items 数据
*/
public function __construct($items = [])
{
$this->items = $this->convertToArray($items);
}
/**
* @param iterable<TKey, TValue>|Collection<TKey, TValue> $items
* @return static<TKey, TValue>
*/
public static function make($items = [])
{
return new static($items);
@@ -45,7 +59,6 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria
/**
* 是否为空
* @access public
* @return bool
*/
public function isEmpty(): bool
@@ -60,6 +73,9 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria
}, $this->items);
}
/**
* @return array<TKey, TValue>
*/
public function all(): array
{
return $this->items;
@@ -68,7 +84,6 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria
/**
* 合并数组
*
* @access public
* @param mixed $items 数据
* @return static
*/
@@ -80,12 +95,11 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria
/**
* 按指定键整理数据
*
* @access public
* @param mixed $items 数据
* @param string $indexKey 键名
* @param string|null $indexKey 键名
* @return array
*/
public function dictionary($items = null, string &$indexKey = null)
public function dictionary($items = null, ?string &$indexKey = null)
{
if ($items instanceof self) {
$items = $items->all();
@@ -107,12 +121,11 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria
/**
* 比较数组,返回差集
*
* @access public
* @param mixed $items 数据
* @param string $indexKey 指定比较的键名
* @return static
* @param string|null $indexKey 指定比较的键名
* @return static<TKey, TValue>
*/
public function diff($items, string $indexKey = null)
public function diff($items, ?string $indexKey = null)
{
if ($this->isEmpty() || is_scalar($this->items[0])) {
return new static(array_diff($this->items, $this->convertToArray($items)));
@@ -135,12 +148,11 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria
/**
* 比较数组,返回交集
*
* @access public
* @param mixed $items 数据
* @param string $indexKey 指定比较的键名
* @return static
* @param string|null $indexKey 指定比较的键名
* @return static<TKey, TValue>
*/
public function intersect($items, string $indexKey = null)
public function intersect($items, ?string $indexKey = null)
{
if ($this->isEmpty() || is_scalar($this->items[0])) {
return new static(array_intersect($this->items, $this->convertToArray($items)));
@@ -163,8 +175,7 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria
/**
* 交换数组中的键和值
*
* @access public
* @return static
* @return static<TValue, TKey>
*/
public function flip()
{
@@ -174,8 +185,7 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria
/**
* 返回数组中所有的键名
*
* @access public
* @return static
* @return static<TKey, TValue>
*/
public function keys()
{
@@ -184,8 +194,7 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria
/**
* 返回数组中所有的值组成的新 Collection 实例
* @access public
* @return static
* @return static<int, TValue>
*/
public function values()
{
@@ -195,8 +204,7 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria
/**
* 删除数组的最后一个元素(出栈)
*
* @access public
* @return mixed
* @return TValue
*/
public function pop()
{
@@ -206,7 +214,6 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria
/**
* 通过使用用户自定义函数,以字符串返回数组
*
* @access public
* @param callable $callback 调用方法
* @param mixed $initial
* @return mixed
@@ -219,8 +226,7 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria
/**
* 以相反的顺序返回数组。
*
* @access public
* @return static
* @return static<TKey, TValue>
*/
public function reverse()
{
@@ -230,8 +236,7 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria
/**
* 删除数组中首个元素,并返回被删除元素的值
*
* @access public
* @return mixed
* @return TValue
*/
public function shift()
{
@@ -240,12 +245,12 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria
/**
* 在数组结尾插入一个元素
* @access public
*
* @param mixed $value 元素
* @param string $key KEY
* @param string|null $key KEY
* @return $this
*/
public function push($value, string $key = null)
public function push($value, ?string $key = null)
{
if (is_null($key)) {
$this->items[] = $value;
@@ -259,7 +264,6 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria
/**
* 把一个数组分割为新的数组块.
*
* @access public
* @param int $size 块大小
* @param bool $preserveKeys
* @return static
@@ -277,12 +281,12 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria
/**
* 在数组开头插入一个元素
* @access public
*
* @param mixed $value 元素
* @param string $key KEY
* @param string|null $key KEY
* @return $this
*/
public function unshift($value, string $key = null)
public function unshift($value, ?string $key = null)
{
if (is_null($key)) {
array_unshift($this->items, $value);
@@ -296,7 +300,7 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria
/**
* 给每个元素执行个回调
*
* @access public
*
* @param callable $callback 回调
* @return $this
*/
@@ -317,9 +321,9 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria
/**
* 用回调函数处理数组中的元素
* @access public
*
* @param callable|null $callback 回调
* @return static
* @return static<TKey, TValue>
*/
public function map(callable $callback)
{
@@ -328,11 +332,11 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria
/**
* 用回调函数过滤数组中的元素
* @access public
*
* @param callable|null $callback 回调
* @return static
* @return static<TKey, TValue>
*/
public function filter(callable $callback = null)
public function filter(?callable $callback = null)
{
if ($callback) {
return new static(array_filter($this->items, $callback));
@@ -343,11 +347,11 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria
/**
* 根据字段条件过滤数组中的元素
* @access public
*
* @param string $field 字段名
* @param mixed $operator 操作符
* @param mixed $value 数据
* @return static
* @return static<TKey, TValue>
*/
public function where(string $field, $operator, $value = null)
{
@@ -405,10 +409,10 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria
/**
* LIKE过滤
* @access public
*
* @param string $field 字段名
* @param string $value 数据
* @return static
* @return static<TKey, TValue>
*/
public function whereLike(string $field, string $value)
{
@@ -417,10 +421,10 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria
/**
* NOT LIKE过滤
* @access public
*
* @param string $field 字段名
* @param string $value 数据
* @return static
* @return static<TKey, TValue>
*/
public function whereNotLike(string $field, string $value)
{
@@ -429,10 +433,10 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria
/**
* IN过滤
* @access public
*
* @param string $field 字段名
* @param array $value 数据
* @return static
* @return static<TKey, TValue>
*/
public function whereIn(string $field, array $value)
{
@@ -441,10 +445,10 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria
/**
* NOT IN过滤
* @access public
*
* @param string $field 字段名
* @param array $value 数据
* @return static
* @return static<TKey, TValue>
*/
public function whereNotIn(string $field, array $value)
{
@@ -453,10 +457,10 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria
/**
* BETWEEN 过滤
* @access public
*
* @param string $field 字段名
* @param mixed $value 数据
* @return static
* @return static<TKey, TValue>
*/
public function whereBetween(string $field, $value)
{
@@ -465,10 +469,10 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria
/**
* NOT BETWEEN 过滤
* @access public
*
* @param string $field 字段名
* @param mixed $value 数据
* @return static
* @return static<TKey, TValue>
*/
public function whereNotBetween(string $field, $value)
{
@@ -477,12 +481,12 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria
/**
* 返回数据中指定的一列
* @access public
*
* @param string|null $columnKey 键名
* @param string|null $indexKey 作为索引值的列
* @return array
*/
public function column( ? string $columnKey, string $indexKey = null)
public function column(?string $columnKey, ?string $indexKey = null)
{
return array_column($this->items, $columnKey, $indexKey);
}
@@ -490,11 +494,10 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria
/**
* 对数组排序
*
* @access public
* @param callable|null $callback 回调
* @return static
* @return static<TKey, TValue>
*/
public function sort(callable $callback = null)
public function sort(?callable $callback = null)
{
$items = $this->items;
@@ -509,7 +512,7 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria
/**
* 指定字段排序
* @access public
*
* @param string $field 排序字段
* @param string $order 排序
* @return $this
@@ -520,15 +523,14 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria
$fieldA = $a[$field] ?? null;
$fieldB = $b[$field] ?? null;
return 'desc' == strtolower($order) ? intval($fieldB > $fieldA) : intval($fieldA > $fieldB);
return 'desc' == strtolower($order) ? ($fieldB <=> $fieldA) : ($fieldA <=> $fieldB);
});
}
/**
* 将数组打乱
*
* @access public
* @return static
* @return static<TKey, TValue>
*/
public function shuffle()
{
@@ -542,12 +544,11 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria
/**
* 获取第一个单元数据
*
* @access public
* @param callable|null $callback
* @param null $default
* @return mixed
* @return TValue
*/
public function first(callable $callback = null, $default = null)
public function first(?callable $callback = null, $default = null)
{
return Arr::first($this->items, $callback, $default);
}
@@ -555,12 +556,11 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria
/**
* 获取最后一个单元数据
*
* @access public
* @param callable|null $callback
* @param null $default
* @return mixed
* @return TValue
*/
public function last(callable $callback = null, $default = null)
public function last(?callable $callback = null, $default = null)
{
return Arr::last($this->items, $callback, $default);
}
@@ -568,30 +568,41 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria
/**
* 截取数组
*
* @access public
* @param int $offset 起始位置
* @param int $length 截取长度
* @param int|null $length 截取长度
* @param bool $preserveKeys preserveKeys
* @return static
* @return static<TKey, TValue>
*/
public function slice(int $offset, int $length = null, bool $preserveKeys = false)
public function slice(int $offset, ?int $length = null, bool $preserveKeys = false)
{
return new static(array_slice($this->items, $offset, $length, $preserveKeys));
}
// ArrayAccess
/**
* @param TKey $key
* @return bool
*/
#[\ReturnTypeWillChange]
public function offsetExists($offset) : bool
{
return array_key_exists($offset, $this->items);
}
/**
* @param TKey $offset
* @return TValue
*/
#[\ReturnTypeWillChange]
public function offsetGet($offset)
{
return $this->items[$offset];
}
/**
* @param TKey|null $offset
* @param TValue $value
* @return void
*/
#[\ReturnTypeWillChange]
public function offsetSet($offset, $value)
{
@@ -602,6 +613,10 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria
}
}
/**
* @param TKey $offset
* @return void
*/
#[\ReturnTypeWillChange]
public function offsetUnset($offset)
{
@@ -614,7 +629,9 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria
return count($this->items);
}
//IteratorAggregate
/**
* @return ArrayIterator<TKey, TValue>
*/
#[\ReturnTypeWillChange]
public function getIterator(): Traversable
{
@@ -630,7 +647,7 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria
/**
* 转换当前数据集为JSON字符串
* @access public
*
* @param integer $options json参数
* @return string
*/
@@ -647,7 +664,6 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSeria
/**
* 转换成数组
*
* @access public
* @param mixed $items 数据
* @return array
*/

View File

@@ -16,12 +16,15 @@ if (!function_exists('throw_if')) {
/**
* 按条件抛异常
*
* @param mixed $condition
* @param Throwable|string $exception
* @param array ...$parameters
* @return mixed
* @template TValue
* @template TException of \Throwable
*
* @throws Throwable
* @param TValue $condition
* @param TException|class-string<TException>|string $exception
* @param mixed ...$parameters
* @return TValue
*
* @throws TException
*/
function throw_if($condition, $exception, ...$parameters)
{
@@ -37,11 +40,15 @@ if (!function_exists('throw_unless')) {
/**
* 按条件抛异常
*
* @param mixed $condition
* @param Throwable|string $exception
* @param array ...$parameters
* @return mixed
* @throws Throwable
* @template TValue
* @template TException of \Throwable
*
* @param TValue $condition
* @param TException|class-string<TException>|string $exception
* @param mixed ...$parameters
* @return TValue
*
* @throws TException
*/
function throw_unless($condition, $exception, ...$parameters)
{
@@ -57,9 +64,11 @@ if (!function_exists('tap')) {
/**
* 对一个值调用给定的闭包,然后返回该值
*
* @param mixed $value
* @param callable|null $callback
* @return mixed
* @template TValue
*
* @param TValue $value
* @param (callable(TValue): mixed)|null $callback
* @return TValue
*/
function tap($value, $callback = null)
{
@@ -77,8 +86,10 @@ if (!function_exists('value')) {
/**
* Return the default value of the given value.
*
* @param mixed $value
* @return mixed
* @template TValue
*
* @param TValue|\Closure(): TValue $value
* @return TValue
*/
function value($value)
{
@@ -277,3 +288,30 @@ if (!function_exists('class_uses_recursive')) {
return array_unique($results);
}
}
if (!function_exists('array_is_list')) {
/**
* 判断数组是否为list
*
* @param array $array 数据
* @return bool
*/
function array_is_list(array $array): bool
{
return array_values($array) === $array;
}
}
if (!function_exists('json_validate')) {
/**
* 判断是否为有效json数据
*
* @param string $string 数据
* @return bool
*/
function json_validate(string $string): bool
{
json_decode($string);
return json_last_error() === JSON_ERROR_NONE;
}
}

View File

@@ -32,9 +32,9 @@ class Arr
/**
* Add an element to an array using "dot" notation if it doesn't exist.
*
* @param array $array
* @param array $array
* @param string $key
* @param mixed $value
* @param mixed $value
* @return array
*/
public static function add($array, $key, $value)
@@ -110,7 +110,7 @@ class Arr
/**
* Flatten a multi-dimensional associative array with dots.
*
* @param array $array
* @param array $array
* @param string $prepend
* @return array
*/
@@ -132,7 +132,7 @@ class Arr
/**
* Get all of the given array except for a specified array of keys.
*
* @param array $array
* @param array $array
* @param array|string $keys
* @return array
*/
@@ -147,7 +147,7 @@ class Arr
* Determine if the given key exists in the provided array.
*
* @param \ArrayAccess|array $array
* @param string|int $key
* @param string|int $key
* @return bool
*/
public static function exists($array, $key)
@@ -162,12 +162,12 @@ class Arr
/**
* Return the first element in an array passing a given truth test.
*
* @param array $array
* @param array $array
* @param callable|null $callback
* @param mixed $default
* @param mixed $default
* @return mixed
*/
public static function first($array, callable $callback = null, $default = null)
public static function first($array, ?callable $callback = null, $default = null)
{
if (is_null($callback)) {
if (empty($array)) {
@@ -191,12 +191,12 @@ class Arr
/**
* Return the last element in an array passing a given truth test.
*
* @param array $array
* @param array $array
* @param callable|null $callback
* @param mixed $default
* @param mixed $default
* @return mixed
*/
public static function last($array, callable $callback = null, $default = null)
public static function last($array, ?callable $callback = null, $default = null)
{
if (is_null($callback)) {
return empty($array) ? value($default) : end($array);
@@ -209,7 +209,7 @@ class Arr
* Flatten a multi-dimensional array into a single level.
*
* @param array $array
* @param int $depth
* @param int $depth
* @return array
*/
public static function flatten($array, $depth = INF)
@@ -234,7 +234,7 @@ class Arr
/**
* Remove one or many array items from a given array using "dot" notation.
*
* @param array $array
* @param array $array
* @param array|string $keys
* @return void
*/
@@ -279,8 +279,8 @@ class Arr
* Get an item from an array using "dot" notation.
*
* @param \ArrayAccess|array $array
* @param string $key
* @param mixed $default
* @param string $key
* @param mixed $default
* @return mixed
*/
public static function get($array, $key, $default = null)
@@ -316,7 +316,7 @@ class Arr
* Check if an item or items exist in an array using "dot" notation.
*
* @param \ArrayAccess|array $array
* @param string|array $keys
* @param string|array $keys
* @return bool
*/
public static function has($array, $keys)
@@ -356,15 +356,13 @@ class Arr
*/
public static function isAssoc(array $array)
{
$keys = array_keys($array);
return array_keys($keys) !== $keys;
return !array_is_list($array);
}
/**
* Get a subset of the items from the given array.
*
* @param array $array
* @param array $array
* @param array|string $keys
* @return array
*/
@@ -376,8 +374,8 @@ class Arr
/**
* Pluck an array of values from an array.
*
* @param array $array
* @param string|array $value
* @param array $array
* @param string|array $value
* @param string|array|null $key
* @return array
*/
@@ -412,7 +410,7 @@ class Arr
/**
* Explode the "value" and "key" arguments passed to "pluck".
*
* @param string|array $value
* @param string|array $value
* @param string|array|null $key
* @return array
*/
@@ -447,9 +445,9 @@ class Arr
/**
* Get a value from the array, and remove it.
*
* @param array $array
* @param array $array
* @param string $key
* @param mixed $default
* @param mixed $default
* @return mixed
*/
public static function pull(&$array, $key, $default = null)
@@ -464,7 +462,7 @@ class Arr
/**
* Get one or a specified number of random values from an array.
*
* @param array $array
* @param array $array
* @param int|null $number
* @return mixed
*
@@ -506,9 +504,9 @@ class Arr
*
* If no key is given to the method, the entire array will be replaced.
*
* @param array $array
* @param array $array
* @param string $key
* @param mixed $value
* @param mixed $value
* @return array
*/
public static function set(&$array, $key, $value)
@@ -540,7 +538,7 @@ class Arr
/**
* Shuffle the given array and return the result.
*
* @param array $array
* @param array $array
* @param int|null $seed
* @return array
*/
@@ -562,7 +560,7 @@ class Arr
/**
* Sort the array using the given callback or "dot" notation.
*
* @param array $array
* @param array $array
* @param callable|string|null $callback
* @return array
*/
@@ -608,7 +606,7 @@ class Arr
/**
* Filter the array using the given callback.
*
* @param array $array
* @param array $array
* @param callable $callback
* @return array
*/
@@ -631,4 +629,41 @@ class Arr
return is_array($value) ? $value : [$value];
}
}
/**
* Recursively merge arrays.
* If the value is an associative array, it will be merged recursively.
* If the value is an indexed array, it will be replaced entirely.
*
* @param array ...$arrays
* @return array
*/
public static function mergeDeep(array ...$arrays): array
{
$result = [];
foreach ($arrays as $array) {
foreach ($array as $key => $value) {
if (isset($result[$key]) && is_array($result[$key]) && is_array($value)) {
// 只有当两个数组都是关联数组时才递归合并
if (self::isAssoc($result[$key]) && self::isAssoc($value)) {
$result[$key] = self::mergeDeep(
$result[$key],
$value
);
} else {
// 如果任一数组是索引数组,则直接覆盖
$result[$key] = $value;
}
} else {
$result[$key] = $value;
}
}
}
return $result;
}
public static function flatMap(callable $fn, array $array): array
{
return array_merge(...array_map($fn, $array));
}
}

View File

@@ -0,0 +1,66 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2015 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: yunwuxin <448901948@qq.com>
// +----------------------------------------------------------------------
namespace think\helper;
use Closure;
use think\exception\FuncNotFoundException;
trait Macroable
{
/**
* 方法注入.
*
* @var Closure[]
*/
protected static $macro = [];
/**
* 设置方法注入.
*
* @param string $method
* @param Closure $closure
*
* @return void
*/
public static function macro(string $method, Closure $closure)
{
static::$macro[$method] = $closure;
}
/**
* 检查方法是否已经有注入
*
* @param string $name
* @return bool
*/
public static function hasMacro(string $method)
{
return isset(static::$macro[$method]);
}
public function __call($method, $args)
{
if (!isset(static::$macro[$method])) {
throw new FuncNotFoundException('method not exists: ' . static::class . '::' . $method . '()', "{static::class}::{$method}");
}
return call_user_func_array(static::$macro[$method]->bindTo($this, static::class), $args);
}
public static function __callStatic($method, $args)
{
if (!isset(static::$macro[$method])) {
throw new FuncNotFoundException('method not exists: ' . static::class . '::' . $method . '()', "{static::class}::{$method}");
}
return call_user_func_array(static::$macro[$method]->bindTo(null, static::class), $args);
}
}

View File

@@ -80,7 +80,7 @@ class Str
* @param string $addChars
* @return string
*/
public static function random(int $length = 6, int $type = null, string $addChars = ''): string
public static function random(int $length = 6, ?int $type = null, string $addChars = ''): string
{
$str = '';
switch ($type) {
@@ -158,7 +158,7 @@ class Str
* @param int|null $length
* @return string
*/
public static function substr(string $string, int $start, int $length = null): string
public static function substr(string $string, int $start, ?int $length = null): string
{
return mb_substr($string, $start, $length, 'UTF-8');
}

View File

@@ -55,7 +55,7 @@ class ArrTest extends TestCase
public function testDivide()
{
list($keys, $values) = Arr::divide(['name' => 'ThinkPHP']);
[$keys, $values] = Arr::divide(['name' => 'ThinkPHP']);
$this->assertSame(['name'], $keys);
$this->assertSame(['ThinkPHP'], $values);
}
@@ -109,7 +109,7 @@ class ArrTest extends TestCase
public function testLast()
{
$array = [100, 200, 300];
$last = Arr::last($array, function ($value) {
$last = Arr::last($array, function ($value) {
return $value < 250;
});
$this->assertSame(200, $last);
@@ -234,17 +234,17 @@ class ArrTest extends TestCase
public function testPull()
{
$array = ['name' => 'ThinkPHP', 'price' => 100];
$name = Arr::pull($array, 'name');
$name = Arr::pull($array, 'name');
$this->assertSame('ThinkPHP', $name);
$this->assertSame(['price' => 100], $array);
// Only works on first level keys
$array = ['i@example.com' => 'Joe', 'jack@localhost' => 'Jane'];
$name = Arr::pull($array, 'i@example.com');
$name = Arr::pull($array, 'i@example.com');
$this->assertSame('Joe', $name);
$this->assertSame(['jack@localhost' => 'Jane'], $array);
// Does not work for nested keys
$array = ['emails' => ['i@example.com' => 'Joe', 'jack@localhost' => 'Jane']];
$name = Arr::pull($array, 'emails.i@example.com');
$name = Arr::pull($array, 'emails.i@example.com');
$this->assertNull($name);
$this->assertSame(['emails' => ['i@example.com' => 'Joe', 'jack@localhost' => 'Jane']], $array);
}
@@ -331,12 +331,42 @@ class ArrTest extends TestCase
public function testWrap()
{
$string = 'a';
$array = ['a'];
$object = new stdClass();
$string = 'a';
$array = ['a'];
$object = new stdClass();
$object->value = 'a';
$this->assertSame(['a'], Arr::wrap($string));
$this->assertSame($array, Arr::wrap($array));
$this->assertSame([$object], Arr::wrap($object));
}
public function testMergeDeep()
{
$this->assertSame(
[
'a' => [
'c' => [2],
'e' => 5,
'f' => 4,
],
'x' => 3,
],
Arr::mergeDeep(
[
'a' => [
'c' => [1],
'e' => 5,
],
'x' => 4,
],
[
'a' => [
'c' => [2],
'f' => 4,
],
'x' => 3,
]
)
);
}
}

View File

@@ -0,0 +1,48 @@
<?php
namespace Tests;
use think\helper\Arr;
class IsAssocTest extends TestCase
{
public function testEmptyArray()
{
// 空数组不是关联数组
$this->assertFalse(Arr::isAssoc([]));
}
public function testSequentialArray()
{
// 顺序索引数组不是关联数组
$this->assertFalse(Arr::isAssoc([1, 2, 3]));
$this->assertFalse(Arr::isAssoc(['a', 'b', 'c']));
$this->assertFalse(Arr::isAssoc([null, false, true]));
}
public function testNonSequentialArray()
{
// 非顺序索引数组是关联数组
$this->assertTrue(Arr::isAssoc([1 => 'a', 0 => 'b'])); // 键顺序不是0,1
$this->assertTrue(Arr::isAssoc([1 => 'a', 2 => 'b'])); // 不是从0开始
$this->assertTrue(Arr::isAssoc([0 => 'a', 2 => 'b'])); // 不连续
}
public function testStringKeys()
{
// 字符串键的数组是关联数组
$this->assertTrue(Arr::isAssoc(['a' => 1, 'b' => 2]));
// 注意PHP会将字符串数字键'0'、'1'自动转换为整数键0、1
// 所以这个实际上是顺序索引数组,不是关联数组
$this->assertFalse(Arr::isAssoc(['0' => 'a', '1' => 'b']));
$this->assertTrue(Arr::isAssoc(['a' => 'a', 0 => 'b'])); // 混合键
}
public function testMixedKeys()
{
// 混合键类型的数组是关联数组
$this->assertTrue(Arr::isAssoc([0 => 'a', 'b' => 'b']));
$this->assertTrue(Arr::isAssoc(['a' => 1, 2 => 'b']));
}
}

View File

@@ -0,0 +1,69 @@
<?php
namespace Tests;
use think\helper\Arr;
class MergeDeepTest extends TestCase
{
public function testMergeDeepWithAssociativeArrays()
{
// 测试关联数组的递归合并
$array1 = ['a' => ['b' => 2], 'c' => 3];
$array2 = ['a' => ['b' => 4, 'd' => 5], 'e' => 6];
$result = Arr::mergeDeep($array1, $array2);
$expected = [
'a' => ['b' => 4, 'd' => 5],
'c' => 3,
'e' => 6
];
$this->assertEquals($expected, $result);
}
public function testMergeDeepWithIndexedArrays()
{
// 测试索引数组的覆盖
$array1 = ['a' => [1, 2, 3], 'b' => 2];
$array2 = ['a' => [4, 5], 'c' => 3];
$result = Arr::mergeDeep($array1, $array2);
$expected = [
'a' => [4, 5], // 索引数组应该被完全覆盖
'b' => 2,
'c' => 3
];
$this->assertEquals($expected, $result);
}
public function testMergeDeepWithMixedArrays()
{
// 测试混合数组类型
$array1 = [
'a' => ['b' => 2, 'c' => 3],
'd' => [1, 2, 3],
'e' => 4
];
$array2 = [
'a' => ['b' => 5, 'f' => 6],
'd' => [7, 8],
'g' => 9
];
$result = Arr::mergeDeep($array1, $array2);
$expected = [
'a' => ['b' => 5, 'c' => 3, 'f' => 6], // 关联数组递归合并
'd' => [7, 8], // 索引数组被覆盖
'e' => 4,
'g' => 9
];
$this->assertEquals($expected, $result);
}
}

View File

@@ -52,12 +52,6 @@ class DbManager
*/
protected $listen = [];
/**
* SQL日志
* @var array
*/
protected $dbLog = [];
/**
* 查询次数
* @var int
@@ -167,8 +161,6 @@ class DbManager
{
if ($this->log) {
$this->log->log($type, $log);
} else {
$this->dbLog[$type][] = $log;
}
}
@@ -180,12 +172,7 @@ class DbManager
*/
public function getDbLog(bool $clear = false): array
{
$logs = $this->dbLog;
if ($clear) {
$this->dbLog = [];
}
return $logs;
return [];
}
/**
@@ -292,16 +279,17 @@ class DbManager
/**
* 更新查询次数
* @deprecated
* @access public
* @return void
*/
public function updateQueryTimes(): void
{
$this->queryTimes++;
}
/**
* 重置查询次数
* @deprecated
* @access public
* @return void
*/
@@ -312,6 +300,7 @@ class DbManager
/**
* 获得查询次数
* @deprecated
* @access public
* @return integer
*/
@@ -340,7 +329,7 @@ class DbManager
{
return $this->listen;
}
/**
* 获取所有连接实列
* @access public

View File

@@ -121,6 +121,12 @@ abstract class Model implements JsonSerializable, ArrayAccess, Arrayable, Jsonab
*/
private $lazySave = false;
/**
* 缓存自动更新标识
* @var bool|string
*/
protected $cacheKey = false;
/**
* Db对象
* @var DbManager
@@ -335,6 +341,18 @@ abstract class Model implements JsonSerializable, ArrayAccess, Arrayable, Jsonab
return $this;
}
/**
* 设置当前查询的自动缓存标识
* @access public
* @param string|bool $key 缓存标识
* @return $this
*/
public function setCacheKey($key)
{
$this->cacheKey = $key;
return $this;
}
/**
* 获取当前模型的数据表后缀
* @access public
@@ -641,7 +659,7 @@ abstract class Model implements JsonSerializable, ArrayAccess, Arrayable, Jsonab
$result = $db->where($where)
->strict(false)
->cache(true)
->cache($this->cacheKey)
->setOption('key', $this->key)
->field($allowFields)
->update($data);
@@ -769,16 +787,20 @@ abstract class Model implements JsonSerializable, ArrayAccess, Arrayable, Jsonab
$pk = $this->getPk();
if (is_string($pk) && $replace) {
$auto = true;
}
$result = [];
$suffix = $this->getSuffix();
foreach ($dataSet as $key => $data) {
if ($this->exists || (!empty($auto) && isset($data[$pk]))) {
if ($replace) {
$exists = true;
foreach ((array) $pk as $field) {
if (!isset($data[$field])) {
$exists = false;
}
}
}
if ($replace && !empty($exists)) {
$result[$key] = static::update($data, [], [], $suffix);
} else {
$result[$key] = static::create($data, $this->field, $this->replace, $suffix);
@@ -809,7 +831,7 @@ abstract class Model implements JsonSerializable, ArrayAccess, Arrayable, Jsonab
$db->transaction(function () use ($where, $db) {
// 删除当前模型数据
$db->where($where)->delete();
$db->where($where)->cache($this->cacheKey)->delete();
// 关联删除
if (!empty($this->relationWrite)) {

View File

@@ -770,10 +770,9 @@ abstract class BaseQuery
* @param mixed $key 缓存key
* @param integer|\DateTime $expire 缓存有效期
* @param string|array $tag 缓存标签
* @param bool $always 始终缓存
* @return $this
*/
public function cache($key = true, $expire = null, $tag = null, bool $always = false)
public function cache($key = true, $expire = null, $tag = null)
{
if (false === $key || !$this->getConnection()->getCache()) {
return $this;
@@ -784,8 +783,7 @@ abstract class BaseQuery
$key = true;
}
$this->options['cache'] = [$key, $expire, $tag];
$this->options['cache_always'] = $always;
$this->options['cache'] = [$key, $expire, $tag ?: $this->getTable()];
return $this;
}
@@ -800,7 +798,23 @@ abstract class BaseQuery
*/
public function cacheAlways($key = true, $expire = null, $tag = null)
{
return $this->cache($key, $expire, $tag, true);
$this->options['cache_always'] = true;
return $this->cache($key, $expire, $tag);
}
/**
* 强制更新缓存
*
* @param mixed $key 缓存key
* @param int|\DateTime $expire 缓存有效期
* @param string|array $tag 缓存标签
*
* @return $this
*/
public function cacheForce($key = true, $expire = null, $tag = null)
{
$this->options['force_cache'] = true;
return $this->cache($key, $expire, $tag);
}
/**
@@ -1026,6 +1040,23 @@ abstract class BaseQuery
return $this->connection->insertAll($this, $dataSet, $limit);
}
/**
* 批量插入记录
* @access public
* @param array $keys 键值
* @param array $values 数据
* @param integer $limit 每次写入数据限制
* @return integer
*/
public function insertAllByKeys(array $keys, array $values, int $limit = 0): int
{
if (empty($limit) && !empty($this->options['limit']) && is_numeric($this->options['limit'])) {
$limit = (int) $this->options['limit'];
}
return $this->connection->insertAllByKeys($this, $keys, $values, $limit);
}
/**
* 通过Select方式插入记录
* @access public

View File

@@ -1238,6 +1238,53 @@ abstract class Builder
);
}
/**
* 生成insertall SQL
* @access public
* @param Query $query 查询对象
* @param array $keys 字段名
* @param array $datas 数据
* @return string
*/
public function insertAllByKeys(Query $query, array $keys, array $datas): string
{
$options = $query->getOptions();
// 获取绑定信息
$bind = $query->getFieldsBindType();
$fields = [];
$values = [];
foreach ($keys as $field) {
$fields[] = $this->parseKey($query, $field);
}
foreach ($datas as $data) {
foreach ($data as $key => &$val) {
if (!$query->isAutoBind()) {
$val = PDO::PARAM_STR == $bind[$keys[$key]] ? '\'' . $val . '\'' : $val;
} else {
$val = $this->parseDataBind($query, $keys[$key], $val, $bind);
}
}
$values[] = 'SELECT ' . implode(',', $data);
}
return str_replace(
['%INSERT%', '%TABLE%', '%EXTRA%', '%FIELD%', '%DATA%', '%COMMENT%'],
[
!empty($options['replace']) ? 'REPLACE' : 'INSERT',
$this->parseTable($query, $options['table']),
$this->parseExtra($query, $options['extra']),
implode(' , ', $fields),
implode(' UNION ALL ', $values),
$this->parseComment($query, $options['comment']),
],
$this->insertAllSql
);
}
/**
* 生成slect insert SQL
* @access public

View File

@@ -309,7 +309,7 @@ class Fetch
$this->query->setOption('soft_delete', null);
$this->query->setOption('data', [$field => $condition]);
// 生成删除SQL语句
$sql = $this->builder->delete($this->query);
$sql = $this->builder->update($this->query);
return $this->fetch($sql);
}
}

View File

@@ -622,15 +622,14 @@ abstract class PDOConnection extends Connection
* @access public
* @param BaseQuery $query 查询对象
* @param string $sql sql指令
* @param array $bind 参数绑定
* @param Model|null $model 模型对象实例
* @param null $condition 查询条件
* @return \Generator
* @throws DbException
*/
public function getCursor(BaseQuery $query, string $sql, array $bind = [], $model = null, $condition = null)
public function getCursor(BaseQuery $query, string $sql, $model = null, $condition = null)
{
$this->queryPDOStatement($query, $sql, $bind);
$this->queryPDOStatement($query, $sql);
// 返回结果集
while ($result = $this->PDOStatement->fetch($this->fetchType)) {
@@ -653,7 +652,7 @@ abstract class PDOConnection extends Connection
*/
public function query(string $sql, array $bind = [], bool $master = false): array
{
return $this->pdoQuery($this->newQuery(), $sql, $bind, $master);
return $this->pdoQuery($this->newQuery()->bind($bind), $sql, $master);
}
/**
@@ -666,7 +665,7 @@ abstract class PDOConnection extends Connection
*/
public function execute(string $sql, array $bind = []): int
{
return $this->pdoExecute($this->newQuery(), $sql, $bind, true);
return $this->pdoExecute($this->newQuery()->bind($bind), $sql, true);
}
/**
@@ -674,25 +673,27 @@ abstract class PDOConnection extends Connection
* @access protected
* @param BaseQuery $query 查询对象
* @param mixed $sql sql指令
* @param array $bind 参数绑定
* @param bool $master 主库读取
* @return array
* @throws DbException
*/
protected function pdoQuery(BaseQuery $query, $sql, array $bind = [], bool $master = null): array
protected function pdoQuery(BaseQuery $query, $sql, bool $master = null): array
{
// 分析查询表达式
$query->parseOptions();
$bind = $query->getBind();
if ($query->getOptions('cache')) {
// 检查查询缓存
$cacheItem = $this->parseCache($query, $query->getOptions('cache'));
$key = $cacheItem->getKey();
if (!$query->getOptions('force_cache')) {
$key = $cacheItem->getKey();
$data = $this->cache->get($key);
$data = $this->cache->get($key);
if (null !== $data) {
return $data;
if (null !== $data) {
return $data;
}
}
}
@@ -730,11 +731,10 @@ abstract class PDOConnection extends Connection
*/
public function pdo(BaseQuery $query): PDOStatement
{
$bind = $query->getBind();
// 生成查询SQL
$sql = $this->builder->select($query);
return $this->queryPDOStatement($query, $sql, $bind);
return $this->queryPDOStatement($query, $sql);
}
/**
@@ -806,18 +806,17 @@ abstract class PDOConnection extends Connection
* @access protected
* @param BaseQuery $query 查询对象
* @param string $sql sql指令
* @param array $bind 参数绑定
* @param bool $origin 是否原生查询
* @return int
* @throws DbException
*/
protected function pdoExecute(BaseQuery $query, string $sql, array $bind = [], bool $origin = false): int
protected function pdoExecute(BaseQuery $query, string $sql, bool $origin = false): int
{
if ($origin) {
$query->parseOptions();
}
$this->queryPDOStatement($query->master(true), $sql, $bind);
$this->queryPDOStatement($query->master(true), $sql);
if (!$origin && !empty($this->config['deploy']) && !empty($this->config['read_master'])) {
$this->readMaster = true;
@@ -844,13 +843,13 @@ abstract class PDOConnection extends Connection
/**
* @param BaseQuery $query
* @param string $sql
* @param array $bind
* @return PDOStatement
* @throws DbException
*/
protected function queryPDOStatement(BaseQuery $query, string $sql, array $bind = []): PDOStatement
protected function queryPDOStatement(BaseQuery $query, string $sql): PDOStatement
{
$options = $query->getOptions();
$bind = $query->getBind();
$master = !empty($options['master']) ? true : false;
$procedure = !empty($options['procedure']) ? true : in_array(strtolower(substr(trim($sql), 0, 4)), ['call', 'exec']);
@@ -898,7 +897,7 @@ abstract class PDOConnection extends Connection
$condition = $options['where']['AND'] ?? null;
// 执行查询操作
return $this->getCursor($query, $sql, $query->getBind(), $query->getModel(), $condition);
return $this->getCursor($query, $sql, $query->getModel(), $condition);
}
/**
@@ -938,7 +937,7 @@ abstract class PDOConnection extends Connection
$sql = $this->builder->insert($query);
// 执行操作
$result = '' == $sql ? 0 : $this->pdoExecute($query, $sql, $query->getBind());
$result = '' == $sql ? 0 : $this->pdoExecute($query, $sql);
if ($result) {
$sequence = $options['sequence'] ?? null;
@@ -977,13 +976,12 @@ abstract class PDOConnection extends Connection
*/
public function insertAll(BaseQuery $query, array $dataSet = [], int $limit = 0): int
{
$query->parseOptions();
if (!is_array(reset($dataSet))) {
return 0;
}
$options = $query->parseOptions();
$replace = !empty($options['replace']);
if (0 === $limit && count($dataSet) >= 5000) {
$limit = 1000;
}
@@ -997,8 +995,8 @@ abstract class PDOConnection extends Connection
$count = 0;
foreach ($array as $item) {
$sql = $this->builder->insertAll($query, $item, $replace);
$count += $this->pdoExecute($query, $sql, $query->getBind());
$sql = $this->builder->insertAll($query, $item);
$count += $this->pdoExecute($query, $sql);
}
// 提交事务
@@ -1011,9 +1009,56 @@ abstract class PDOConnection extends Connection
return $count;
}
$sql = $this->builder->insertAll($query, $dataSet, $replace);
$sql = $this->builder->insertAll($query, $dataSet);
return $this->pdoExecute($query, $sql, $query->getBind());
return $this->pdoExecute($query, $sql);
}
/**
* 批量插入记录
* @access public
* @param BaseQuery $query 查询对象
* @param array $keys 键值
* @param array $values 数据
* @param integer $limit 每次写入数据限制
* @return integer
* @throws \Exception
* @throws \Throwable
*/
public function insertAllByKeys(BaseQuery $query, array $keys, array $values, int $limit = 0): int
{
$query->parseOptions();
if (0 === $limit && count($values) >= 5000) {
$limit = 1000;
}
if ($limit) {
// 分批写入 自动启动事务支持
$this->startTrans();
try {
$array = array_chunk($values, $limit, true);
$count = 0;
foreach ($array as $item) {
$sql = $this->builder->insertAllByKeys($query, $keys, $item);
$count += $this->pdoExecute($query, $sql);
}
// 提交事务
$this->commit();
} catch (\Exception | \Throwable $e) {
$this->rollback();
throw $e;
}
return $count;
}
$sql = $this->builder->insertAllByKeys($query, $keys, $values);
return $this->pdoExecute($query, $sql);
}
/**
@@ -1032,7 +1077,7 @@ abstract class PDOConnection extends Connection
$sql = $this->builder->selectInsert($query, $fields, $table);
return $this->pdoExecute($query, $sql, $query->getBind());
return $this->pdoExecute($query, $sql);
}
/**
@@ -1050,7 +1095,7 @@ abstract class PDOConnection extends Connection
$sql = $this->builder->update($query);
// 执行操作
$result = '' == $sql ? 0 : $this->pdoExecute($query, $sql, $query->getBind());
$result = '' == $sql ? 0 : $this->pdoExecute($query, $sql);
if ($result) {
$this->db->trigger('after_update', $query);
@@ -1075,7 +1120,7 @@ abstract class PDOConnection extends Connection
$sql = $this->builder->delete($query);
// 执行操作
$result = $this->pdoExecute($query, $sql, $query->getBind());
$result = $this->pdoExecute($query, $sql);
if ($result) {
$this->db->trigger('after_delete', $query);
@@ -1109,10 +1154,13 @@ abstract class PDOConnection extends Connection
if (!empty($options['cache'])) {
$cacheItem = $this->parseCache($query, $options['cache'], 'value');
$key = $cacheItem->getKey();
if ($this->cache->has($key)) {
return $this->cache->get($key);
if (!$query->getOptions('force_cache')) {
$key = $cacheItem->getKey();
if ($this->cache->has($key)) {
return $this->cache->get($key);
}
}
}
@@ -1208,10 +1256,12 @@ abstract class PDOConnection extends Connection
if (!empty($options['cache'])) {
// 判断查询缓存
$cacheItem = $this->parseCache($query, $options['cache'], 'column');
$name = $cacheItem->getKey();
if (!$query->getOptions('force_cache')) {
$name = $cacheItem->getKey();
if ($this->cache->has($name)) {
return $this->cache->get($name);
if ($this->cache->has($name)) {
return $this->cache->get($name);
}
}
}
@@ -1545,17 +1595,16 @@ abstract class PDOConnection extends Connection
* @access public
* @param BaseQuery $query 查询对象
* @param array $sqlArray SQL批处理指令
* @param array $bind 参数绑定
* @return bool
*/
public function batchQuery(BaseQuery $query, array $sqlArray = [], array $bind = []): bool
public function batchQuery(BaseQuery $query, array $sqlArray = []): bool
{
// 自动启动事务支持
$this->startTrans();
try {
foreach ($sqlArray as $sql) {
$this->pdoExecute($query, $sql, $bind);
$this->pdoExecute($query, $sql);
}
// 提交事务
$this->commit();

View File

@@ -111,8 +111,6 @@ class Mongo
$result[$item] = $val;
} elseif (isset($val[0]) && 'exp' == $val[0]) {
$result[$item] = $val[1];
} elseif (is_null($val)) {
$result[$item] = 'NULL';
} else {
$result[$item] = $this->parseValue($query, $val, $key);
}

View File

@@ -12,6 +12,7 @@ declare (strict_types = 1);
namespace think\db\builder;
use PDO;
use think\db\Builder;
use think\db\exception\DbException as Exception;
use think\db\Query;
@@ -27,7 +28,7 @@ class Mysql extends Builder
* @var array
*/
protected $parser = [
'parseCompare' => ['=', '<>', '>', '>=', '<', '<='],
'parseCompare' => ['=', '!=', '<>', '>', '>=', '<', '<='],
'parseLike' => ['LIKE', 'NOT LIKE'],
'parseBetween' => ['NOT BETWEEN', 'BETWEEN'],
'parseIn' => ['NOT IN', 'IN'],
@@ -146,10 +147,9 @@ class Mysql extends Builder
* @access public
* @param Query $query 查询对象
* @param array $dataSet 数据集
* @param bool $replace 是否replace
* @return string
*/
public function insertAll(Query $query, array $dataSet, bool $replace = false): string
public function insertAll(Query $query, array $dataSet): string
{
$options = $query->getOptions();
@@ -183,7 +183,55 @@ class Mysql extends Builder
return str_replace(
['%INSERT%', '%EXTRA%', '%TABLE%', '%PARTITION%', '%FIELD%', '%DATA%', '%DUPLICATE%', '%COMMENT%'],
[
$replace ? 'REPLACE' : 'INSERT',
!empty($options['replace']) ? 'REPLACE' : 'INSERT',
$this->parseExtra($query, $options['extra']),
$this->parseTable($query, $options['table']),
$this->parsePartition($query, $options['partition']),
implode(' , ', $fields),
implode(' , ', $values),
$this->parseDuplicate($query, $options['duplicate']),
$this->parseComment($query, $options['comment']),
],
$this->insertAllSql
);
}
/**
* 生成insertall SQL
* @access public
* @param Query $query 查询对象
* @param array $keys 键值
* @param array $values 数据
* @return string
*/
public function insertAllByKeys(Query $query, array $keys, array $datas): string
{
$options = $query->getOptions();
// 获取绑定信息
$bind = $query->getFieldsBindType();
$fields = [];
$values = [];
foreach ($keys as $field) {
$fields[] = $this->parseKey($query, $field);
}
foreach ($datas as $data) {
foreach ($data as $key => &$val) {
if (!$query->isAutoBind()) {
$val = PDO::PARAM_STR == $bind[$keys[$key]] ? '\'' . $val . '\'' : $val;
} else {
$val = $this->parseDataBind($query, $keys[$key], $val, $bind);
}
}
$values[] = '( ' . implode(',', $data) . ' )';
}
return str_replace(
['%INSERT%', '%EXTRA%', '%TABLE%', '%PARTITION%', '%FIELD%', '%DATA%', '%DUPLICATE%', '%COMMENT%'],
[
!empty($options['replace']) ? 'REPLACE' : 'INSERT',
$this->parseExtra($query, $options['extra']),
$this->parseTable($query, $options['table']),
$this->parsePartition($query, $options['partition']),

View File

@@ -49,12 +49,21 @@ trait AggregateQuery
}
$options = $this->getOptions();
$subSql = $this->options($options)
if (isset($options['cache'])) {
$cache = $options['cache'];
unset($options['cache']);
}
$subSql = $this->options($options)
->field('count(' . $field . ') AS think_count')
->bind($this->bind)
->buildSql();
$query = $this->newQuery()->table([$subSql => '_group_count_']);
$query = $this->newQuery();
if (isset($cache)) {
$query->setOption('cache', $cache);
}
$query->table([$subSql => '_group_count_']);
$count = $query->aggregate('COUNT', '*');
} else {

View File

@@ -258,7 +258,7 @@ class Mongo extends Connection
$this->queryStartTime = microtime(true);
if ($session = $this->getSession()) {
$this->cursor = $this->mongo->executeQuery($namespace, $query, [
$this->cursor = $this->mongo->executeQuery($namespace, $mongoQuery, [
'readPreference' => is_null($readPreference) ? new ReadPreference(ReadPreference::RP_PRIMARY) : $readPreference,
'session' => $session,
]);

View File

@@ -264,7 +264,7 @@ class HasMany extends Relation
// 保存关联表数据
$data[$this->foreignKey] = $this->parent->{$this->localKey};
return new $this->model($data);
return (new $this->model($data))->setSuffix($this->getModel()->getSuffix());
}
/**

View File

@@ -151,14 +151,10 @@ class HasOneThrough extends HasManyThrough
->select();
// 组装模型数据
$data = [];
$keys = array_flip($keys);
foreach ($list as $set) {
$data[$keys[$set->{$this->throughKey}]] = $set;
}
return $data;
return array_map(function ($key) use ($list) {
$set = $list->where($this->throughKey, '=', $key)->first();
return $set ? clone $set : null;
}, $keys);
}
}

View File

@@ -315,7 +315,7 @@ class MorphMany extends Relation
$data[$this->morphKey] = $this->parent->$pk;
$data[$this->morphType] = $this->type;
return new $this->model($data);
return (new $this->model($data))->setSuffix($this->getModel()->getSuffix());
}
/**

View File

@@ -284,7 +284,7 @@ class MorphOne extends Relation
$data[$this->morphKey] = $this->parent->$pk;
$data[$this->morphType] = $this->type;
return new $this->model($data);
return (new $this->model($data))->setSuffix($this->getModel()->getSuffix());
}
/**

View File

@@ -224,7 +224,7 @@ abstract class OneToOne extends Relation
// 保存关联表数据
$data[$this->foreignKey] = $this->parent->{$this->localKey};
return new $this->model($data);
return (new $this->model($data))->setSuffix($this->getModel()->getSuffix());
}
/**