From 265a80905da59e836798225c4dc5e0109a29e534 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sat, 23 Apr 2016 20:26:26 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=AD=A3BELONGS=5FTO=E5=85=B3?= =?UTF-8?q?=E8=81=94=E6=9F=A5=E8=AF=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 10 +++++----- library/think/model/Relation.php | 15 +++++++++++---- 2 files changed, 16 insertions(+), 9 deletions(-) diff --git a/library/think/Model.php b/library/think/Model.php index ac6ea029..008dcf66 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -729,17 +729,17 @@ abstract class Model implements \JsonSerializable, \ArrayAccess * BELONGS TO 关联定义 * @access public * @param string $model 模型名 - * @param string $localKey 关联主键 * @param string $foreignKey 关联外键 + * @param string $otherKey 关联主键 * @return \think\db\Query|string */ - public function belongsTo($model, $localKey = '', $foreignKey = '') + public function belongsTo($model, $foreignKey = '', $otherKey = '') { // 记录当前关联信息 $model = $this->parseModel($model); - $foreignKey = $foreignKey ?: $this->pk; - $localKey = $localKey ?: Loader::parseName(basename(str_replace('\\', '/', $model))) . '_id'; - return $this->relation->belongsTo($model, $foreignKey, $localKey); + $foreignKey = $foreignKey ?: Loader::parseName(basename(str_replace('\\', '/', $model))) . '_id'; + $otherKey = $otherKey ?: (new $model)->getPk(); + return $this->relation->belongsTo($model, $foreignKey, $otherKey); } /** diff --git a/library/think/model/Relation.php b/library/think/model/Relation.php index dde02931..9fc23218 100644 --- a/library/think/model/Relation.php +++ b/library/think/model/Relation.php @@ -74,7 +74,6 @@ class Relation // 判断关联类型执行查询 switch ($this->type) { case self::HAS_ONE: - case self::BELONGS_TO: $result = $relation->where($foreignKey, $this->parent->$localKey)->find(); if (false === $result) { $class = $this->model; @@ -82,6 +81,14 @@ class Relation $result->$foreignKey = $this->parent->$localKey; } break; + case self::BELONGS_TO: + $result = $relation->where($localKey, $this->parent->$foreignKey)->find(); + if (false === $result) { + $class = $this->model; + $result = new $class; + $result->$localKey = $this->parent->$foreignKey; + } + break; case self::HAS_MANY: $result = $relation->where($foreignKey, $this->parent->$localKey)->select(); break; @@ -368,17 +375,17 @@ class Relation * BELONGS TO 关联定义 * @access public * @param string $model 模型名 - * @param string $localKey 关联主键 * @param string $foreignKey 关联外键 + * @param string $localKey 关联主键 * @return \think\db\Query|string */ - public function belongsTo($model, $localKey, $foreignKey) + public function belongsTo($model, $foreignKey, $otherKey) { // 记录当前关联信息 $this->type = self::BELONGS_TO; $this->model = $model; $this->foreignKey = $foreignKey; - $this->localKey = $localKey; + $this->localKey = $otherKey; // 返回关联的模型对象 return $this;