From f39c6627daeb2c05ea8da01fa5de42101bb41e81 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Thu, 21 Apr 2016 17:56:20 +0800 Subject: [PATCH] =?UTF-8?q?=E6=94=B9=E8=BF=9BModel=E7=B1=BB=E7=9A=84=20has?= =?UTF-8?q?=E5=92=8ChasWhere=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 33 +++++++++++++++++++-------------- 1 file changed, 19 insertions(+), 14 deletions(-) diff --git a/library/think/Model.php b/library/think/Model.php index cda95775..501be6fa 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -601,13 +601,12 @@ abstract class Model implements \JsonSerializable, \ArrayAccess */ public static function has($relation, $operator = '>=', $count = 1, $id = '*') { - $class = new static(); - $model = $class->$relation(); - $info = $class->getRelationInfo(); - $result = $model->group($info['foreignKey']) - ->having('count(' . $id . ')' . $operator . $count) - ->column($info['foreignKey']); - return self::db()->where($info['localKey'], 'in', $result); + $class = new static(); + $model = $class->$relation(); + $info = $class->getRelationInfo(); + $table = $info['model']::getTable(); + return self::db()->alias('a')->join($table . ' b', 'a.' . $info['localKey'] . '=b.' . $info['foreignKey'])->group('b.' . $info['foreignKey']) + ->having('count(' . $id . ')' . $operator . $count); } /** @@ -619,13 +618,19 @@ abstract class Model implements \JsonSerializable, \ArrayAccess */ public static function hasWhere($relation, $where = []) { - $class = new static(); - $model = $class->$relation(); - $info = $class->getRelationInfo(); - $result = $model->group($info['foreignKey']) - ->where($where) - ->column($info['foreignKey']); - return self::db()->where($info['localKey'], 'in', $result); + $class = new static(); + $model = $class->$relation(); + $info = $class->getRelationInfo(); + $table = $info['model']::getTable(); + if (is_array($where)) { + foreach ($where as $key => $val) { + if (false === strpos($key, '.')) { + $where['b.' . $key] = $val; + unset($where[$key]); + } + } + } + return self::db()->alias('a')->field('a.*')->join($table . ' b', 'a.' . $info['localKey'] . '=b.' . $info['foreignKey'])->where($where); } /**