改进Relation类的getRelation方法 支持在关联定义方法中使用where条件或者其他的操作Query操作方法

This commit is contained in:
thinkphp
2016-05-29 12:09:21 +08:00
parent 14de14a1eb
commit c9846a51e1

View File

@@ -78,48 +78,45 @@ class Relation
$relation = $this->parent->$name(); $relation = $this->parent->$name();
$foreignKey = $this->foreignKey; $foreignKey = $this->foreignKey;
$localKey = $this->localKey; $localKey = $this->localKey;
if ($relation instanceof Relation) {
// 判断关联类型执行查询 // 判断关联类型执行查询
switch ($this->type) { switch ($this->type) {
case self::HAS_ONE: case self::HAS_ONE:
$result = $relation->where($foreignKey, $this->parent->$localKey)->find(); $result = $relation->where($foreignKey, $this->parent->$localKey)->find();
break; break;
case self::BELONGS_TO: case self::BELONGS_TO:
$result = $relation->where($localKey, $this->parent->$foreignKey)->find(); $result = $relation->where($localKey, $this->parent->$foreignKey)->find();
break; break;
case self::HAS_MANY: case self::HAS_MANY:
$result = $relation->select(); $result = $relation->select();
break; break;
case self::HAS_MANY_THROUGH: case self::HAS_MANY_THROUGH:
$result = $relation->select(); $result = $relation->select();
break; break;
case self::BELONGS_TO_MANY: case self::BELONGS_TO_MANY:
// 关联查询 // 关联查询
$pk = $this->parent->getPk(); $pk = $this->parent->getPk();
$condition['pivot.' . $localKey] = $this->parent->$pk; $condition['pivot.' . $localKey] = $this->parent->$pk;
$result = $this->belongsToManyQuery($relation, $this->middle, $foreignKey, $localKey, $condition)->select(); $result = $this->belongsToManyQuery($relation, $this->middle, $foreignKey, $localKey, $condition)->select();
foreach ($result as $set) { foreach ($result as $set) {
$pivot = []; $pivot = [];
foreach ($set->toArray() as $key => $val) { foreach ($set->toArray() as $key => $val) {
if (strpos($key, '__')) { if (strpos($key, '__')) {
list($name, $attr) = explode('__', $key, 2); list($name, $attr) = explode('__', $key, 2);
if ('pivot' == $name) { if ('pivot' == $name) {
$pivot[$attr] = $val; $pivot[$attr] = $val;
unset($set->$key); unset($set->$key);
}
} }
} }
$set->pivot = new Pivot($pivot, $this->middle);
} }
break; $set->pivot = new Pivot($pivot, $this->middle);
default: }
// 直接返回 break;
$result = $relation; default:
} // 直接返回
return $result; $result = $relation;
} else {
return $relation;
} }
return $result;
} }
/** /**