{"id":21126152,"url":"https://github.com/shigebeyond/ci-orm","last_synced_at":"2026-05-22T05:06:11.570Z","repository":{"id":85816083,"uuid":"177725674","full_name":"shigebeyond/ci-orm","owner":"shigebeyond","description":"基于CI 即codeigniter框架2.1.4版本，做的ORM扩展类","archived":false,"fork":false,"pushed_at":"2019-04-12T00:47:47.000Z","size":17,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-01-21T05:41:53.669Z","etag":null,"topics":["ci","codeigniter","orm"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/shigebeyond.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2019-03-26T06:12:12.000Z","updated_at":"2019-04-12T00:47:48.000Z","dependencies_parsed_at":null,"dependency_job_id":"43efee5a-c216-43f4-aa56-1cd9e2159e31","html_url":"https://github.com/shigebeyond/ci-orm","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/shigebeyond%2Fci-orm","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/shigebeyond%2Fci-orm/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/shigebeyond%2Fci-orm/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/shigebeyond%2Fci-orm/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/shigebeyond","download_url":"https://codeload.github.com/shigebeyond/ci-orm/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243573168,"owners_count":20312879,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ci","codeigniter","orm"],"created_at":"2024-11-20T04:39:29.341Z","updated_at":"2026-05-22T05:06:11.533Z","avatar_url":"https://github.com/shigebeyond.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"# 概述\n\n基于[CI](http://codeigniter.com/user_guide/) 即codeigniter框架2.1.4版本，做的ORM扩展类。\n\n对象关系映射（Object Relational Mapping 简称ORM）允许你把数据库中的数据当成一个PHP对象来操纵和控制。\n\n一旦你定义了ORM和你的数据库中数据的关系，那么无论你用任何你喜欢的方式操纵数据，以及保存结果到数据库，都不需要使用SQL语言。\n\n通过创建按照配置约定的模型之间的关系，大部分从数据库中重复的编写创建，读取，更新和删除信息的查询可以被减少或者完全消除。\n\n所有的关系都能被自动用ORM库来处理并且你可以像使用标准对象属性一样访问相关数据。\n\n# 定义模型 \n\n## 简单 \n\n如果你的数据库和名称使用默认的约定（数据库使用default，名称使用类名中去掉_model后缀的部分），则模型可以像这样简单的定义：\n\n```\nrequire COMPATH.\"core/Sk_Model.php\";\n\nclass User_model extends Sk_Model {\n}\n```\n\n## 定制 \n\n一些基本模型属性的定义：\n\n```\n/**\n * 试客vip(充值余额)模型类\n */\nclass user_model extends Sk_Model {\n\n    /**\n     * 表名称(不带前缀)\n     * @var string\n     */\n    public $table = 'user';\n\n    /**\n     * 主键\n     * @var int\n     */\n    public $key = 'uid';\n\n    /**\n     * 数据库连接配置 (string or array)\n     *\n     * @var mixed\n     * @access protected\n     */\n    protected $db_con = 'slave'; // 数据库配置名,如 default 或 slave 或 uc\n}\n```\n\n# 切换db \n\n如切换主从库, uc库\n\n```\n$this-\u003eload-\u003emodel ( 'user_model' );\n//读写分离\n$this-\u003euser_model-\u003eset_db_con('slave');\n```\n\n# 读 \n\n使用 Sk_model::find()和 Sk_model::find_all()方法调用来取得记录。\n\n## 读单个 \n\n获取用户名为Bob的首条活跃用户：\n\n```\n$this-\u003eload-\u003emodel ( 'user_model' );\n$uid = 1;\n$user = $this-\u003euser_model-\u003ewhere('uid', $uid)-\u003efind();\n// 等价于\n$user = $this-\u003euser_model-\u003efind($uid);\n// 等价于\n$user = $this-\u003euser_model-\u003efind_by('uid', $uid);\n// 等价于\n$user = $this-\u003euser_model-\u003efind_by(array('uid' =\u003e $uid));\n```\n\n## 读多个 \n\n获取所有叫Bob的用户（多条记录）：\n\n```\n$this-\u003eload-\u003emodel ( 'user_model' );\n$users = $this-\u003euser_model-\u003ewhere('uid \u003e', 1)-\u003efind_all();\n// 等价于\n$users = $this-\u003euser_model-\u003efind_all_by('uid \u003e', 1);\n// 等价于\n$users = $this-\u003euser_model-\u003efind_all_by(array('uid \u003e' =\u003e 1));\n```\n\n当你使用 Sk_model::find_all 检索了模型列表，你可以遍历它们作为你的数据库结果来使用：\n\n```\nforeach ($users as $user) {\n  ...\n}\n```\n\n## 查询生成器(query builder) \n\nSk_model 代理调用了　CI_DB_active_record　的方法\n\n注意，如果你还不明白CI_DB_active_record库的查询生成器，你可以参考[CI的Active Record 类](http://codeigniter.org.cn/user_guide/database/active_record.html)\n\n```\n$this-\u003eload-\u003emodel ( 'user_model' );\n$users = $this-\u003euser_model\n              -\u003ewhere('sex', 1)     // where sex = 1\n              -\u003ewhere('id \u003e', 1)      // where id \u003e 1\n              -\u003elike('name', 'shige') // where name like '%shige%'\n              -\u003efind();\n```\n\n## 统计行数 \n\n```\n$this-\u003eload-\u003emodel ( 'user_model' );\n// 统计全部\n$n = $this-\u003euser_model-\u003ecount_all();\n\n// 统计男性\n$n = $this-\u003euser_model-\u003ecount_all_by('sex', 1);\n// 等价于\n$n = $this-\u003euser_model-\u003ecount_all_by(array('sex' =\u003e 1));\n// 等价于\n$n = $this-\u003euser_model-\u003ewhere('sex', 1)-\u003ecount_all();\n```\n\n# 写 \n\n## 插入 \n\n```\n$this-\u003eload-\u003emodel ( 'user_model' );\n$user = array('uname' =\u003e 'Joe');\n$result = $this-\u003euser_model-\u003einsert($user);\nif ($result) {\n    ... insert success\n} else {\n    ... insert fail\n    $error = $this-\u003euser_model-\u003eerror;\n}\n```\n\n## 更新 \n\n```\n$this-\u003eload-\u003emodel ( 'user_model' );\n$uid = 1;\n$user = $this-\u003euser_model-\u003efind($uid);\n$user['uname'] = 'Joe';\n$result = $this-\u003euser_model-\u003eupdate($uid, $user);\n// 等价于\n$result = $this-\u003euser_model-\u003eupdate(array('uid' =\u003e $uid), $user);\n// 等价于\n$result = $this-\u003euser_model-\u003ewhere('uid', $uid)-\u003eupdate(array(), $user);\nif ($result) {\n    ... save success\n} else {\n    ... save fail\n    $error = $this-\u003euser_model-\u003eerror;\n}\n```\n\n# 删除 \n\n## 删除记录 \n\n使用 Sk_model::delete() 来删除记录。\n\n```\n$this-\u003eload-\u003emodel ( 'user_model' );\n$id = 1;\n$result = $this-\u003euser_model-\u003edelete($id);\n// 等价于\n$result = $this-\u003euser_model-\u003edelete(array('uid' =\u003e $uid));\n// 等价于\n$result = $this-\u003euser_model-\u003ewhere('uid', $uid)-\u003edelete();\nif ($result) {\n    ... delete success\n} else {\n    ... delete fail\n    $error = $this-\u003euser_model-\u003eerror;\n}\n```\n\n# 模型验证(Validation) \n\n如果你还不了解CI的校验器CI_Form_validation请参考[表单验证详解](http://codeigniter.org.cn/user_guide/libraries/form_validation.html)\n\n你可以使用 $_validation_rules 来列出规则与过滤器，他是一个数组，格式参考[表单验证-使用数组设置验证规则](http://codeigniter.org.cn/user_guide/libraries/form_validation.html#validationrulesasarray)\n\n**TODO:** 考虑添加xss_clean的过滤器\n\n```\nclass User_model extends Sk_model\n{\n    ... \n    \n    /** @var array Validation rules. */\n    protected $validation_rules = array(\n    array(\n        'field' =\u003e 'id',\n        'label' =\u003e '身份证',\n        'rules' =\u003e 'required|trim|max_length[11]',\n    ), \n    array(\n        'field' =\u003e 'name',\n        'label' =\u003e '姓名',\n        'rules' =\u003e 'required|trim|max_length[255]',\n    ),\n    array(\n        'field' =\u003e 'birthday',\n        'label' =\u003e '生日',\n        'rules' =\u003e 'required|trim|max_length[10]|is_numeric',\n    ),\n    );\n}\n```\n\n用法：\n\n```\n$this-\u003eload-\u003emodel ( 'user_model' );\n$uid = 1;\n$user = $this-\u003euser_model-\u003efind($uid);\n$user['uname'] = 'Joe';\n$result = $this-\u003euser_model-\u003eupdate($uid, $user);\nif ($result) {\n    ... save success\n} else {\n    ... save fail\n    $error = $this-\u003euser_model-\u003eerror ? $this-\u003euser_model-\u003eerror : validation_errors();\n}\n```\n\n其中 $this-\u003euser_model-\u003eerror 是保存的错误，validation_errors() 是校验的错误\n\n# 关联关系 \n\n我们支持了3种对象关联关系：\n```\nbelongs_to\nhas_many\nhas_one\n```\n\n## belongs_to \n\n用于一对一/多对一。\n\n当一个模型从属于另外的模型时，你可以使用关联关系 belongs_to。\n\n如一个文章从属于一个用户（作者）：Post 模型从属于 User 模型。\n\n```\nPost_model extends Sk_model\n{\n    protected $_belongs_to = array(\n        'author' =\u003e array(                // 别名：用于访问关联模型\n            'model'       =\u003e 'User_model',// 模型：从属于哪个模型\n            'foreign_key' =\u003e 'author_id', // 外键\n        ),\n    );\n}\n```\n\n## has_many \n\n用于一对多。\n\n关联关系 has_many 其实就是关联关系 belongs_to 的反面，表示某个模型拥有多个另外的模型。\n\n在上面的例子，一个文章从属于一个用户。而从用户角度，一个用户拥有多个文章：User 模型拥有多个 Post 模型。\n\n```\nUser_model extends Sk_model\n{\n    protected $_has_many = array(\n        'posts' =\u003e array(                  // 别名，用于访问关联模型\n            'model'       =\u003e 'Post_model', // 模型：拥有哪个模型\n            'foreign_key' =\u003e 'author_id',  // 外键\n            'order' =\u003e 'dateline desc' // 排序，仅has_many的一对多的关系才有排序，一对一不需要排序\n        ),\n    );\n}\n```\n\n## has_one \n\n关联关系 has_one 类似于关联关系 has_many，但它只能是一对一。\n\n如果一个用户只能有一个文章。\n\n```\nUser_model extends Sk_model\n{\n    protected $_has_one = array(\n        'post' =\u003e array(                  // 别名，用于访问关联模型\n            'model'       =\u003e 'Post_model', // 模型：拥有哪个模型\n            'foreign_key' =\u003e 'author_id',  // 外键\n        ),\n    );\n}\n```\n\n## 关联查询 \n\n**通过 with() 关联查询**\n\n```\n$this-\u003eload-\u003emodel ( 'user_model' );\n$uid = 1;\n$user = $this-\u003euser_model-\u003ewith('post')-\u003efind(); // 联查sql：select * from user, post where user.id = $uid and post.author_id = user.id\n\n// 直接通过关联关系的别名作为属性, 来获得关联的文章\n$post = $user['post'];\n```\n\n**with()不能适用的场景**\n\nwith()不能用在两个关联的model的表属于不同数据库的场景，如上所见，不能生成跨库的联查sql\n\n## 只查关联对象 \n\n只查关联表\n\n```\n$this-\u003eload-\u003emodel ( 'user_model' );\n$uid = 1;\n// 查一个\n$post = $this-\u003euser_model-\u003efind_related($uid, 'post'); // 联查sql：select * from post where author_id = $uid\n\n// 查多个\n$posts = $this-\u003euser_model-\u003efind_all_related($uid, 'post'); // 联查sql：select * from post where author_id = $uid\n\n// 查行数\n$post_count = $this-\u003euser_model-\u003ecount_related($uid, 'post'); // 联查sql：select count(1) from post where author_id = $uid\n```\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fshigebeyond%2Fci-orm","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fshigebeyond%2Fci-orm","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fshigebeyond%2Fci-orm/lists"}