diff --git a/library/think/Model.php b/library/think/Model.php index 0e633c54..c69d48c3 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -1237,9 +1237,9 @@ abstract class Model implements \JsonSerializable, \ArrayAccess { $model = new static(); if (is_array($operator) || $operator instanceof \Closure) { - return $model->$relation()->hasWhere($model, $operator); + return $model->$relation()->hasWhere($operator); } - return $model->$relation()->has($model, $operator, $count, $id); + return $model->$relation()->has($operator, $count, $id); } /** @@ -1252,7 +1252,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess public static function hasWhere($relation, $where = []) { $model = new static(); - return $model->$relation()->hasWhere($model, $where); + return $model->$relation()->hasWhere($where); } /** diff --git a/library/think/model/relation/HasMany.php b/library/think/model/relation/HasMany.php index 60bd1677..bf2e2757 100644 --- a/library/think/model/relation/HasMany.php +++ b/library/think/model/relation/HasMany.php @@ -212,16 +212,15 @@ class HasMany extends Relation /** * 根据关联条件查询当前模型 * @access public - * @param Model $model 模型对象 * @param string $operator 比较操作符 * @param integer $count 个数 * @param string $id 关联表的统计字段 * @return Query */ - public function has($model, $operator = '>=', $count = 1, $id = '*') + public function has($operator = '>=', $count = 1, $id = '*') { $table = $this->query->getTable(); - return $model->db()->alias('a') + return $this->parent->db()->alias('a') ->join($table . ' b', 'a.' . $this->localKey . '=b.' . $this->foreignKey, $this->joinType) ->group('b.' . $this->foreignKey) ->having('count(' . $id . ')' . $operator . $count); @@ -230,24 +229,25 @@ class HasMany extends Relation /** * 根据关联条件查询当前模型 * @access public - * @param Model $model 模型对象 - * @param mixed $where 查询条件(数组或者闭包) + * @param mixed $where 查询条件(数组或者闭包) * @return Query */ - public function hasWhere($model, $where = []) + public function hasWhere($where = []) { - $table = $this->query->getTable(); + $table = $this->query->getTable(); + $model = basename(str_replace('\\', '/', get_class($this->parent))); + $relation = basename(str_replace('\\', '/', $this->model)); if (is_array($where)) { foreach ($where as $key => $val) { if (false === strpos($key, '.')) { - $where['b.' . $key] = $val; + $where[$relation . '.' . $key] = $val; unset($where[$key]); } } } - return $model->db()->alias('a') - ->field('a.*') - ->join($table . ' b', 'a.' . $this->localKey . '=b.' . $this->foreignKey, $this->joinType) + return $this->parent->db()->alias($model) + ->field($model . '.*') + ->join($table . ' ' . $relation, $model . '.' . $this->localKey . '=' . $relation . '.' . $this->foreignKey, $this->joinType) ->where($where); }