From b89991dc41fb4d341e29da35443ebe19b181cef1 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Thu, 21 Apr 2016 14:44:14 +0800 Subject: [PATCH] =?UTF-8?q?Model=E7=B1=BB=E5=A2=9E=E5=8A=A0has=E5=92=8Chas?= =?UTF-8?q?Where=E6=96=B9=E6=B3=95=E7=94=A8=E4=BA=8E=E6=A0=B9=E6=8D=AE?= =?UTF-8?q?=E5=85=B3=E8=81=94=E8=A1=A8=E7=9A=84=E6=9D=A1=E4=BB=B6=E6=9D=A5?= =?UTF-8?q?=E6=9F=A5=E8=AF=A2=E5=BD=93=E5=89=8D=E6=A8=A1=E5=9E=8B=E6=95=B0?= =?UTF-8?q?=E6=8D=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/library/think/Model.php b/library/think/Model.php index 005e26da..cda95775 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -590,6 +590,44 @@ abstract class Model implements \JsonSerializable, \ArrayAccess return $model; } + /** + * 根据关联条件查询当前模型 + * @access public + * @param string $relation 关联方法名 + * @param string $operator 比较操作符 + * @param integer $count 个数 + * @param string $id 关联表的统计字段 + * @return \think\Model + */ + 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); + } + + /** + * 根据关联条件查询当前模型 + * @access public + * @param string $relation 关联方法名 + * @param mixed $where 查询条件(数组或者闭包) + * @return \think\Model + */ + 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); + } + /** * 解析模型的完整命名空间 * @access public