数据库之AR Active Record (AR) 是一个流行的 对象-关系映射 (ORM) 技术。 每个 AR 类代表一个数据表(或视图),数据表(或视图)的列在 AR 类中体现为类的属性,一个 AR 实例则表示表中的一行。 – yiichina 数据库之AR gii CRUD C C实现原理 R R实现原理
数据库之AR
Active Record (AR) 是一个流行的 对象-关系映射 (ORM) 技术。 每个 AR 类代表一个数据表(或视图),数据表(或视图)的列在 AR 类中体现为类的属性,一个 AR 实例则表示表中的一行。
– yiichina
- 数据库之AR
- gii
- CRUD
- C
- C实现原理
- R
- R实现原理
- U
- U实现原理
- D
- D实现原理
- 场景和新纪录
gii
这里简单提一下gii 具体百度一下,你就知道
是YII的代码生成工具
下面使用的User类就是gii生成的
CRUD
C
<code><span>public</span> <span><span>function</span> <span>actionCreate</span><span>()</span> {</span> <span>//$user = new User; //实例化userModel</span> <span>//或</span> <span>//$user = User::model();</span> <span>//$user->setIsNewRecord(true);</span> <span>//给对应的字段赋值</span> <span>$user</span>->username = <span>"框架"</span>; <span>$user</span>->status = <span>0</span>; <span>$user</span>->city = <span>5</span>; <span>//插入数据</span> <span>//这里值得细说的是 IsNewRecord变量为true</span> <span>//场景(scenario)为insert </span> <span>//具体看 实现原理</span> <span>if</span>(<span>$user</span>->save()) { <span>echo</span> <span>'插入成功'</span>; }<span>else</span> { var_dump(<span>$user</span>->errors); } }</code>
C实现原理
实例化 User model
<code><span>$user</span> = <span>new</span> User;</code>
User extends CActiveRecord 调用 CActiveRecord的构造方法
<code><span>public</span> function __construct(<span>$scenario</span><span>=</span><span>'insert'</span>) { <span>//使用 静态方法 model实例化对象 场景(scenario)为空</span> <span>if</span>(<span>$scenario</span><span>===</span><span>null</span>) <span>// internally used by populateRecord() and model()</span> <span>return</span>; <span>$this</span><span>-></span>setScenario(<span>$scenario</span>); <span>//设置场景为 insert</span> <span>$this</span><span>-></span>setIsNewRecord(<span>true</span>); <span>//设置 这个一条新纪录</span> <span>//获得字段的默认值</span> <span>$this</span><span>-></span>_attributes<span>=</span><span>$this</span><span>-></span>getMetaData()<span>-></span>attributeDefaults; <span>$this</span><span>-></span>init(); <span>//一个空方法 子类可以自己重写</span> <span>$this</span><span>-></span>attachBehaviors(<span>$this</span><span>-></span>behaviors()); <span>//绑定行为</span> <span>$this</span><span>-></span>afterConstruct(); <span>//触发 构造结束事件</span> }</code>
R
<code><span>public</span> <span><span>function</span> <span>actionRead</span><span>()</span> {</span> <span>$user</span> = User::model()->find(); <span>//这里的场景(Scenario)仍然是update哦</span> <span>$user</span> = User::model()->find(<span>'id = :id'</span>,<span>array</span>(<span>':id'</span>=><span>5</span>)); var_dump(<span>$user</span>); } <span>public</span> <span><span>function</span> <span>actionReadAll</span><span>()</span> {</span> <span>$user</span> = User::model()->findAll(); <span>$user</span> = User::model()->findAll(<span>'id > :lid and id ,<span>array</span>(<span>':lid'</span>=><span>5</span>,<span>':mid'</span>=><span>10</span>)); var_dump(<span>$user</span>); } <span>public</span> <span><span>function</span> <span>actionReadCriteria</span><span>()</span> {</span> <span>$criteria</span> = <span>new</span> CDbCriteria(); <span>// $criteria->addCondition('id > :lid');</span> <span>// $criteria->addCondition('id <span>// $criteria->addBetweenCondition('id', 5, 10); //包含 5 和 10</span> <span>// $criteria->addInCondition('id',array(4,5,6)); </span> <span>// $criteria->params = array(':lid'=>5,':mid'=>10);</span> <span>$criteria</span>->addSearchCondition(<span>'username'</span>, <span>'g%'</span> ,<span>false</span>); <span>$criteria</span>->addSearchCondition(<span>'username'</span>, <span>'g'</span>); <span>$criteria</span>->order = <span>'id desc'</span>; <span>// $criteria->limit = 2;</span> <span>// $criteria->offset = 1;</span> <span>$user</span> = User::model()->findAll(<span>$criteria</span>); var_dump(<span>$user</span>); }</span></span></code>
R实现原理
find()和findall()
<code><span>//创建一个 条件对象 CDbCriteria类</span> <span>$criteria</span>=<span>$this</span>->getCommandBuilder() ->createCriteria(<span>$condition</span>,<span>$params</span>); <span>//查询</span> <span>return</span> <span>$this</span>->query(<span>$criteria</span>,<span>true</span>);</code>
U
<code><span>public</span> <span><span>function</span> <span>actionUpdate</span><span>()</span> {</span> <span>$id</span> = Yii::app()->request->getParam(<span>'id'</span>); <span>$user</span> = User::model()->findByPk(<span>$id</span>); <span>$user</span>->username = <span>"被我改了吧"</span>; <span>//这里值得细说的是 IsNewRecord变量为false</span> <span>//场景(scenario)为update</span> <span>//具体看 实现原理</span> <span>if</span>(<span>$user</span>->save()) { <span>echo</span> <span>'修改成功'</span>; }<span>else</span> { var_dump(<span>$user</span>->errors); } }</code>
U实现原理
<code><span>$user</span> = User::model()->findByPk(<span>$id</span>);</code>
调用的User的 静态方法model
<code><span>public</span> <span>static</span> <span><span>function</span> <span>model</span><span>(<span>$className</span>=__CLASS__)</span> {</span> <span>return</span> <span>parent</span>::model(<span>$className</span>); }</code>
调用父类 CActiveRecord 类的 model方法
<code><span>public</span> <span>static</span> <span><span>function</span> <span>model</span><span>(<span>$className</span>=__CLASS__)</span> {</span> <span>if</span>(<span>isset</span>(<span>self</span>::<span>$_models</span>[<span>$className</span>])) <span>return</span> <span>self</span>::<span>$_models</span>[<span>$className</span>]; <span>else</span> { <span>//实例化类</span> <span>$model</span>=<span>self</span>::<span>$_models</span>[<span>$className</span>]=<span>new</span> <span>$className</span>(<span>null</span>); <span>//绑定行为</span> <span>$model</span>->attachBehaviors(<span>$model</span>->behaviors()); <span>return</span> <span>$model</span>; } }</code>
D
<code><span>public</span> <span><span>function</span> <span>actionDelete</span><span>()</span> {</span> <span>$id</span> = Yii::app()->request->getParam(<span>'id'</span>); <span>$user</span> = User::model()->findByPk(<span>$id</span>); <span>if</span>(<span>$user</span>->delete()) { <span>echo</span> <span>'删除成功'</span>; } <span>else</span> { var_dump(<span>$user</span>->errors); } }</code>
D实现原理
没有什么特别的
<code><span>if</span>(<span>!</span><span>$this</span><span>-></span>getIsNewRecord()) { Yii<span>::trace</span>(get_class(<span>$this</span>)<span>.</span><span>'.delete()'</span>,<span>'system.db.ar.CActiveRecord'</span>); <span>if</span>(<span>$this</span><span>-></span>beforeDelete()) { <span>$result</span><span>=</span><span>$this</span><span>-></span>deleteByPk(<span>$this</span><span>-></span>getPrimaryKey())<span>></span><span>0</span>; <span>$this</span><span>-></span>afterDelete(); <span>return</span> <span>$result</span>; } <span>else</span> <span>return</span> <span>false</span>; }</code>
场景和新纪录
场景(scenario)
新纪录(IsNewRecord)
1.场景的作用更多体现在 insert 和 update上,这也是默认的场景只有insert和update
new User()
场景被赋值成insert
User::model()
在 query()
的时候 调用 populateRecords()
赋值成update
节选自yiichina网友的一片博文,比较好的描述了yii中场景的作用
2.新纪录一般用来区别insert和其他操作

InnoDB uses redologs and undologs to ensure data consistency and reliability. 1.redologs record data page modification to ensure crash recovery and transaction persistence. 2.undologs records the original data value and supports transaction rollback and MVCC.

Key metrics for EXPLAIN commands include type, key, rows, and Extra. 1) The type reflects the access type of the query. The higher the value, the higher the efficiency, such as const is better than ALL. 2) The key displays the index used, and NULL indicates no index. 3) rows estimates the number of scanned rows, affecting query performance. 4) Extra provides additional information, such as Usingfilesort prompts that it needs to be optimized.

Usingtemporary indicates that the need to create temporary tables in MySQL queries, which are commonly found in ORDERBY using DISTINCT, GROUPBY, or non-indexed columns. You can avoid the occurrence of indexes and rewrite queries and improve query performance. Specifically, when Usingtemporary appears in EXPLAIN output, it means that MySQL needs to create temporary tables to handle queries. This usually occurs when: 1) deduplication or grouping when using DISTINCT or GROUPBY; 2) sort when ORDERBY contains non-index columns; 3) use complex subquery or join operations. Optimization methods include: 1) ORDERBY and GROUPB

MySQL/InnoDB supports four transaction isolation levels: ReadUncommitted, ReadCommitted, RepeatableRead and Serializable. 1.ReadUncommitted allows reading of uncommitted data, which may cause dirty reading. 2. ReadCommitted avoids dirty reading, but non-repeatable reading may occur. 3.RepeatableRead is the default level, avoiding dirty reading and non-repeatable reading, but phantom reading may occur. 4. Serializable avoids all concurrency problems but reduces concurrency. Choosing the appropriate isolation level requires balancing data consistency and performance requirements.

MySQL is suitable for web applications and content management systems and is popular for its open source, high performance and ease of use. 1) Compared with PostgreSQL, MySQL performs better in simple queries and high concurrent read operations. 2) Compared with Oracle, MySQL is more popular among small and medium-sized enterprises because of its open source and low cost. 3) Compared with Microsoft SQL Server, MySQL is more suitable for cross-platform applications. 4) Unlike MongoDB, MySQL is more suitable for structured data and transaction processing.

MySQL index cardinality has a significant impact on query performance: 1. High cardinality index can more effectively narrow the data range and improve query efficiency; 2. Low cardinality index may lead to full table scanning and reduce query performance; 3. In joint index, high cardinality sequences should be placed in front to optimize query.

The MySQL learning path includes basic knowledge, core concepts, usage examples, and optimization techniques. 1) Understand basic concepts such as tables, rows, columns, and SQL queries. 2) Learn the definition, working principles and advantages of MySQL. 3) Master basic CRUD operations and advanced usage, such as indexes and stored procedures. 4) Familiar with common error debugging and performance optimization suggestions, such as rational use of indexes and optimization queries. Through these steps, you will have a full grasp of the use and optimization of MySQL.

MySQL's real-world applications include basic database design and complex query optimization. 1) Basic usage: used to store and manage user data, such as inserting, querying, updating and deleting user information. 2) Advanced usage: Handle complex business logic, such as order and inventory management of e-commerce platforms. 3) Performance optimization: Improve performance by rationally using indexes, partition tables and query caches.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version
Visual web development tools

Atom editor mac version download
The most popular open source editor