From 3c57c610dc7387f929c5ca7b85fd54b4c8f08b9e Mon Sep 17 00:00:00 2001 From: thinkphp Date: Thu, 9 Jun 2016 10:30:04 +0800 Subject: [PATCH] =?UTF-8?q?=E9=A2=84=E8=BD=BD=E5=85=A5=E6=9F=A5=E8=AF=A2?= =?UTF-8?q?=E6=94=AF=E6=8C=81=E6=8C=87=E5=AE=9A=E5=AD=97=E6=AE=B5=E6=9F=A5?= =?UTF-8?q?=E8=AF=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/db/Query.php | 36 ++++++++++++++++++++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) diff --git a/library/think/db/Query.php b/library/think/db/Query.php index fcd67bd3..b1c50e13 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -1377,17 +1377,33 @@ class Query $name = Loader::parseName(basename(str_replace('\\', '/', $currentModel))); $table = $this->getTable(); $alias = isset($info['alias'][$name]) ? $info['alias'][$name] : $name; - $this->table($table)->alias($alias)->field(true, false, $table, $alias); + $this->table($table)->alias($alias); + if (isset($this->options['field'])) { + $field = $this->options['field']; + unset($this->options['field']); + } else { + $field = true; + } + $this->field($field, false, $table, $alias); } // 预载入封装 $joinTable = $model->getTable(); $joinName = Loader::parseName(basename(str_replace('\\', '/', $info['model']))); $joinAlias = isset($info['alias'][$joinName]) ? $info['alias'][$joinName] : $joinName; $this->via($joinAlias); - $this->join($joinTable . ' ' . $joinAlias, $alias . '.' . $info['localKey'] . '=' . $joinAlias . '.' . $info['foreignKey'])->field(true, false, $joinTable, $joinAlias, $joinName . '__'); + $this->join($joinTable . ' ' . $joinAlias, $alias . '.' . $info['localKey'] . '=' . $joinAlias . '.' . $info['foreignKey']); if ($closure) { // 执行闭包查询 call_user_func_array($closure, [ & $this]); + + //指定获取关联的字段 + //需要在 回调中 调方法 withField 方法,如 + // $query->where(['id'=>1])->withField('id,name'); + if (!empty($this->options['with_field'])) { + $field = $this->options['with_field']; + unset($this->options['with_field']); + } + $this->field($field, false, $joinTable, $joinAlias, $joinName . '__'); } $i++; } elseif ($closure) { @@ -1399,6 +1415,22 @@ class Query return $this; } + /** + * 关联预加载中 获取关联指定字段值 + * example: + * Model::with(['relation' => function($query){ + * $query->withField("id,name"); + * }]) + * + * @param string | array $field 指定获取的字段 + * @return $this + */ + public function withField($field) + { + $this->options['with_field'] = $field; + return $this; + } + /** * 设置当前字段添加的表别名 * @access public