PHPackages                             watsonhaw/think-orm - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. watsonhaw/think-orm

ActiveLibrary[Database &amp; ORM](/categories/database)

watsonhaw/think-orm
===================

the PHP Database&amp;ORM Framework

v3.1.3(2d ago)0136Apache-2.0PHPPHP &gt;=8.1

Since Oct 27Pushed 5mo agoCompare

[ Source](https://github.com/watsonhaw5566/think-orm)[ Packagist](https://packagist.org/packages/watsonhaw/think-orm)[ RSS](/packages/watsonhaw-think-orm/feed)WikiDiscussions master Synced today

READMEChangelog (1)Dependencies (9)Versions (156)Used By (0)

ThinkORM
========

[](#thinkorm)

基于 PHP 8.0+ 和 PDO 实现的轻量级 ORM，支持多数据库、参数绑定、模型关联等功能。3.x 版本采用 PHP 强类型实现，专注于高性能与类型安全。

[![License](https://camo.githubusercontent.com/798509b4df525f56802b56f8096862487f08023e3d7561c68656f8dab10d0d6e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4170616368652d2d322e302d626c75652e737667)](LICENSE)[![PHP Version](https://camo.githubusercontent.com/e11f2a8dee4d9b3e9b74ecd0d8abe795d1519d3fd471add331b91f205d6ceb9a/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253345253344382e302d707572706c652e737667)](composer.json)[![Tests](https://camo.githubusercontent.com/15ab8f421ae6f78863d80cafb397acb15c5fbef37fa058dbadb5a1a185d46953/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f74657374732d3538253230756e6974253230253242253230696e746567726174696f6e2d677265656e2e737667)](#%E6%B5%8B%E8%AF%95)

主要特性
----

[](#主要特性)

- **强类型实现**：基于 PHP 8.0+ 与强类型系统
- **PDO 抽象层**：支持 MySQL / MariaDB / PostgreSQL / SQLite / SQL Server / Oracle / MongoDb
- **查询构造器**：链式查询、原生 SQL、自动参数绑定
- **高级查询**：`WHERE IN`、`BETWEEN`、`LIKE`、子查询、JOIN、UNION、聚合
- **JSON 查询**：MySQL JSON 字段的 `field->key` 语法
- **模型系统**：字段类型转换、访问器/修改器、软删除、乐观锁、时间戳
- **关联模型**：一对一、一对多、多对多、多态关联、预载入、延迟关联
- **事务机制**：完整事务支持、保存点（Savepoint）、断点重连
- **分布式支持**：主从分离、读写分离、多数据库动态切换
- **规范兼容**：`PSR-16` 缓存规范、`PSR-3` 日志规范
- **数据库日志**：完整 SQL 执行日志与监听接口

支持的数据库
------

[](#支持的数据库)

驱动类名说明MySQL / MariaDB`mysql`完整 JSON 字段、事务支持PostgreSQL`pgsql`支持SQLite`sqlite`支持SQL Server`sqlsrv`支持Oracle`oracle`支持MongoDB`mongo`需要 `ext-mongodb` 扩展安装
--

[](#安装)

通过 Composer 安装：

```
composer require watsonhaw/think-orm
```

系统要求：

- PHP **8.0** 或更高版本
- `ext-pdo` 及对应数据库的 PDO 驱动
- `ext-json`
- （可选）`ext-mongodb` 用于 MongoDB 支持

快速开始
----

[](#快速开始)

```
use think\facade\Db;

// 配置数据库连接
Db::setConfig([
    'default' => 'mysql',
    'connections' => [
        'mysql' => [
            'type'     => 'mysql',
            'hostname' => 'localhost',
            'database' => 'your_db',
            'username' => 'root',
            'password' => '',
            'hostport' => '3306',
            'charset'  => 'utf8mb4',
        ],
    ],
]);

// 查询构造器
$users = Db::table('user')
    ->where('status', 1)
    ->where('age', '>', 18)
    ->order('id', 'desc')
    ->limit(10)
    ->select();

// 模型
class User extends \think\Model
{
    protected $name = 'user';
}

$user = User::find(1);
$user->name = 'New Name';
$user->save();
```

核心组件
----

[](#核心组件)

```
src/
├── DbManager.php       # 数据库管理器 (Db Facade 的实现)
├── Model.php           # 模型基类
├── Paginator.php       # 分页器
├── db/                 # 数据库核心层
│   ├── Connection.php  # 连接基类 (SQL 生成与参数绑定)
│   ├── Query.php       # 查询构造器
│   ├── Builder.php     # SQL 语法构建器
│   ├── builder/        # 各数据库方言
│   ├── connector/      # 各数据库连接器
│   └── concern/        # 查询 concern (ParamsBind, Transaction, WhereQuery 等)
├── model/              # 模型层
│   ├── relation/       # 关联关系 (HasOne, HasMany, BelongsTo 等)
│   └── concern/        # 模型 concern (TimeStamp, SoftDelete, OptimLock 等)
└── facade/             # 门面 (Facade)

```

测试
--

[](#测试)

本项目包含 **65 个纯单元测试** 与若干集成测试，通过 `@group` 注解分组管理。

### 测试分组

[](#测试分组)

Group描述依赖运行方式`unit`纯单元测试，使用 `MockConnection` 模拟数据库交互无需真实数据库`composer test``database`集成测试，验证与真实数据库的交互需要真实 MySQL 连接`vendor/bin/phpunit --group database`### 常用命令

[](#常用命令)

```
# 运行纯单元测试（默认，无需数据库）
composer test

# 等同于：
vendor/bin/phpunit --group unit

# 只运行数据库集成测试（需要真实 MySQL）
vendor/bin/phpunit --group database

# 运行全部测试
vendor/bin/phpunit
```

### 测试覆盖

[](#测试覆盖)

纯单元测试覆盖以下核心功能：

- ✅ SQL 参数绑定 (`?` 和命名参数)
- ✅ SQL 注入防护（单引号转义）
- ✅ 查询构造器：`SELECT` / `WHERE` / `JOIN` / `LIMIT` / `ORDER` / `GROUP BY`
- ✅ 条件子句：`IN` / `NOT IN` / `BETWEEN` / `LIKE` / `NULL` / `EXP`
- ✅ 聚合函数：`COUNT` / `SUM` / `AVG` / `MAX` / `MIN`
- ✅ 多表连接与别名
- ✅ 表前缀支持
- ✅ 事务与保存点（SQL 生成层面）
- ✅ 行锁 (`FOR UPDATE`)

文档
--

[](#文档)

详细开发指南请参考官方文档： [ThinkORM 开发指南](https://doc.thinkphp.cn/@think-orm)

ThinkPHP 主文档：

License
-------

[](#license)

Apache-2.0

###  Health Score

55

↑

FairBetter than 97% of packages

Maintenance83

Actively maintained with recent releases

Popularity14

Limited adoption so far

Community19

Small or concentrated contributor base

Maturity90

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 78.3% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~20 days

Recently: every ~43 days

Total

155

Last Release

2d ago

Major Versions

v2.0.61 → v3.0.92023-04-20

2.0.x-dev → v3.0.282024-10-10

v3.0.33 → v4.0-beta2024-12-24

v3.0.34 → v4.0.02025-01-23

3.0.x-dev → 4.0.x-dev2025-12-18

PHP version history (4 changes)0.1PHP &gt;=5.6.0

v2.0.0PHP &gt;=7.1.0

v3.0.0PHP &gt;=8.0.0

v3.1.1PHP &gt;=8.1

### Community

Maintainers

![](https://www.gravatar.com/avatar/d52f81ce11644b1118af4d1942981d8c11003c36a0613ba64f162e4c868b057f?d=identicon)[watsonhaw](/maintainers/watsonhaw)

---

Top Contributors

[![liu21st](https://avatars.githubusercontent.com/u/1111670?v=4)](https://github.com/liu21st "liu21st (601 commits)")[![NHZEX](https://avatars.githubusercontent.com/u/14545600?v=4)](https://github.com/NHZEX "NHZEX (40 commits)")[![yunwuxin](https://avatars.githubusercontent.com/u/2168125?v=4)](https://github.com/yunwuxin "yunwuxin (38 commits)")[![big-dream](https://avatars.githubusercontent.com/u/9215157?v=4)](https://github.com/big-dream "big-dream (18 commits)")[![YepYuYu](https://avatars.githubusercontent.com/u/84311710?v=4)](https://github.com/YepYuYu "YepYuYu (11 commits)")[![StyleCIBot](https://avatars.githubusercontent.com/u/11048387?v=4)](https://github.com/StyleCIBot "StyleCIBot (11 commits)")[![Hhh0121](https://avatars.githubusercontent.com/u/127706674?v=4)](https://github.com/Hhh0121 "Hhh0121 (8 commits)")[![season886](https://avatars.githubusercontent.com/u/18523125?v=4)](https://github.com/season886 "season886 (5 commits)")[![4352570](https://avatars.githubusercontent.com/u/51403503?v=4)](https://github.com/4352570 "4352570 (3 commits)")[![phpdog](https://avatars.githubusercontent.com/u/6801280?v=4)](https://github.com/phpdog "phpdog (3 commits)")[![yuanzhihai](https://avatars.githubusercontent.com/u/15060466?v=4)](https://github.com/yuanzhihai "yuanzhihai (3 commits)")[![Tinywan](https://avatars.githubusercontent.com/u/14959876?v=4)](https://github.com/Tinywan "Tinywan (2 commits)")[![9007967](https://avatars.githubusercontent.com/u/33853639?v=4)](https://github.com/9007967 "9007967 (2 commits)")[![evalor](https://avatars.githubusercontent.com/u/26944445?v=4)](https://github.com/evalor "evalor (2 commits)")[![liuqiantech](https://avatars.githubusercontent.com/u/42691767?v=4)](https://github.com/liuqiantech "liuqiantech (2 commits)")[![augushong](https://avatars.githubusercontent.com/u/31880431?v=4)](https://github.com/augushong "augushong (2 commits)")[![zoujingli](https://avatars.githubusercontent.com/u/4349951?v=4)](https://github.com/zoujingli "zoujingli (2 commits)")[![hongfs](https://avatars.githubusercontent.com/u/23376043?v=4)](https://github.com/hongfs "hongfs (2 commits)")[![liuqiandev](https://avatars.githubusercontent.com/u/50485460?v=4)](https://github.com/liuqiandev "liuqiandev (2 commits)")[![woodongwong](https://avatars.githubusercontent.com/u/9292647?v=4)](https://github.com/woodongwong "woodongwong (1 commits)")

---

Tags

databaseorm

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/watsonhaw-think-orm/health.svg)

```
[![Health](https://phpackages.com/badges/watsonhaw-think-orm/health.svg)](https://phpackages.com/packages/watsonhaw-think-orm)
```

###  Alternatives

[cakephp/cakephp

The CakePHP framework

8.9k19.5M1.8k](/packages/cakephp-cakephp)[directorytree/ldaprecord

A fully-featured LDAP ORM.

5793.4M17](/packages/directorytree-ldaprecord)[flow-php/flow

PHP ETL - Extract Transform Load - Data processing framework

85036.3k](/packages/flow-php-flow)[topthink/think-orm

the PHP Database&amp;ORM Framework

4372.1M242](/packages/topthink-think-orm)[cycle/database

DBAL, schema introspection, migration and pagination

71777.8k53](/packages/cycle-database)[shopware/core

Shopware platform is the core for all Shopware ecommerce products.

585.6M574](/packages/shopware-core)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
