$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);