Model类增加has和hasWhere方法用于根据关联表的条件来查询当前模型数据

This commit is contained in:
thinkphp
2016-04-21 14:44:14 +08:00
parent 4602f135f6
commit b89991dc41

View File

@@ -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