tp5 实现类似 withCount方法() 的 withSum()方法

本文介绍了一种在ORM框架中实现自定义统计求和的方法,通过在Query.php和HasMany.php文件中添加特定方法,可以对关联模型进行统计求和操作。详细解释了withSum方法的参数及使用方式,并提供了在model中定义关联关系的例子。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.Query.php 文件中添加如下方法:

/**
     * @param $relation model中关联方法
     * @param bool $subQuery 是否是有子查询
     * @param string $sum 统计生成后缀
     * @param bool $left_alias  左表别名
     * @return $this
     */
    public function withSum($relation, $subQuery = true, $sum='num',$left_alias=false)
    {
        if (!$subQuery) {
            $this->options['with_sum'] = $relation;
        } else {
            $relations = is_string($relation) ? explode(',', $relation) : $relation;
            if (!isset($this->options['field'])) {
                $this->field('*');
            }
            foreach ($relations as $key => $relation) {
                $closure = false;
                if ($relation instanceof \Closure) {
                    $closure  = $relation;
                    $relation = $key;
                }
                $relation = Loader::parseName($relation, 1, false);
                $count    = '(' . (new $this->model)->$relation()->getRelationSumQuery($closure, $sum,$left_alias) . ')';
                $this->field([$count => Loader::parseName($relation) . '_sum']);
            }
        }
        return $this;
    }

2.HasMany.php中添加如下方法:

    public function getRelationSumQuery($closure, $sum,$left_alias)
    {
        if($left_alias)
        {
            $table = $left_alias;
        }
        else
        {
            $table = $this->parent->getTable();
        }

        if ($closure) {
            call_user_func_array($closure, [ & $this->query]);
        }

        return $this->query->where([
            $this->foreignKey => [
                'exp',
                '=' . $table . '.' . $this->parent->getPk(),
            ],
        ])->fetchSql()->sum($sum);
    }

3.model 中添加关联 如

    //自定义统计求和
    public function stock()
    {
        return $this->hasMany('Stock','device_id');
    }

4.逻辑中调用:

$result = $this->modelDevice
            ->alias('a')
            ->withSum('stock',true,'num','a')//自定义统计sum方法
            ->join($join)
            ->where($where)
            ->field($field)
            ->order($order)
            ->paginate($paginate);

withSum('stock',true,'num','a') 参数说明

stock model 中关联方法

true 是否使用字查询

num 查询完成后 字段为 stock_num

a    如果存在alias 设置 关联sum的左表 alias

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值