【TP5.1】 关联查询时,如何指定具体的字段信息

在ThinkPHP5.1框架中,进行关联查询时,若要指定显示特定字段,需要清除默认的字段选项。不这样做可能会导致额外的主表和关联表字段信息显示,甚至在MySQL 5.7以上版本出现`group_full`错误。解决方案是在查询时使用`removeOption('field')`来清空字段选项。

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

$this->model
                ->with(['Task'])
                ->alias(['__TASK__'=>'task'])
                ->where($where)
                ->removeOption('field')
                ->field('max(a) , sum(b) )
                ->find();

在关联查询时,如果需要自定义field(仅显示自定义field),需要增加 removeOption('field') 对字段进行清空

 

如果清空,会造成的影响:

1、除了自定义的字段以外,还会显示主表字段信息、关联表字段信息

2、如果有聚合操作,在mysql5.7以上版本,会提示sql group_full报错

 

TP5.1源代码:

Query类

/**
     * 设置关联查询JOIN预查询
     * @access public
     * @param  string|array $with 关联方法名称
     * @return $this
     */
    public function with($with)
    {
        if (empty($with)) {
            return $this;
        }

        if (is_string($with)) {
            $with = explode(',', $with);
        }

        $first = true;

        /** @var Model $class */
        $class = $this->model;
        foreach ($with as $key => $relation) {
            $closure = null;

            if ($relation instanceof \Closure) {
                // 支持闭包查询过滤关联条件
                $closure  = $relation;
                $relation = $key;
            } elseif (is_array($relation)) {
                $relation = $key;
            } elseif (is_string($relation) && strpos($relation, '.')) {
                list($relation, $subRelation) = explode('.', $relation, 2);
            }

            /** @var Relation $model */
            $relation = Loader::parseName($relation, 1, false);
            $model    = $class->$relation();

            if ($model instanceof OneToOne && 0 == $model->getEagerlyType()) {
                $table = $model->getTable();
                $model->removeOption()
                    ->table($table)
                    ->eagerly($this, $relation, true, '', $closure, $first);
                $first = false;
            }
        }

        $this->via();

        $this->options['with'] = $with;

        return $this;
    }

 

重点部分:

->eagerly($this, $relation, true, '', $closure, $first);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值