Yii good schema Design Guide

Source: Internet
Author: User
CActiveRecord is widely used in Yii applications. the design focuses on optimization rather than complex SQL statements. In fact, most of them are designed to use friendly SQL modes to solve practical problems.

CActiveRecord is widely used in Yii applications. the design focuses on optimization rather than complex SQL statements. In fact, most of them are designed to use friendly SQL modes to solve practical problems.

The most common method is to create code that is easy to read and understand. for exampleMeaningBut this is hard to do.

When you seek help from a forum or on the '# yii' channel, using a strange name means you have a lot of trouble: explaining what the code is doing. Sometimes your problem cannot be effectively solved.

A bunch of consistency problems.

However, these are only tests, not rules. your code will still work if you do not follow these rules, but your code will be simpler if you follow these rules.

Use the singular number instead of the plural number to name the table name.


We thinkSQL tableContains many records, oneModel)It's just one of them. it's strange to use $ model = new Comments () anywhere to define a link again.

Name your table "comment" instead of "comments", "invoice" instead of "invoices. The same is true for model classes (Comment, Invoice, and so on ).

If you cannot change the database mode, but at least you can change the name of the Yii model class, in this case, you should add an additional COMMENT // COMMENT to the code to remind the user.

Do not add a table name before the field name


The following method is very common in the traditional SQL design mode, but it is because the combination of ActiveRecord is always lengthy and complex. In the category table:

1234567891011 -- Not available -- you can create table category (category_id INTEGER ..., id INTEGER ..., category_name VARCHAR ..., name VARCHAR ..., category_value INTEGER value INTEGER );); // unfriendly // friendly $ model-> category_id $ model-> id $ model-> category_name $ model-> name $ model-> category_value $ model-> value

Although SQL statements generated using this long method are easier to understand, it is not convenient to use them in ActiveRecord.

Do not show the table name prefix in the class name of the model class.

Yii supports table prefixes, which are used inAllApplications are stored in a shared host and shared with a database. your blog table prefix is blog _, and the table prefix of the timing application is time. they exist in the same database and cannot conflict with each other.

The prefix tbl _ is often seen in many tutorials and examples.

However, classes do not need to contain these prefixes, because there is no need to avoid conflicts: Your blog application and your timing application use two different applications.

12 ClassTblCommentextendsCActiveRecord {// classCommentextendsCActiveRecord cannot be obtained {// optional

The undefined prefix in the code makes people very disgusted.

Make sure that the primary key of each table is id


Most tables have a unique host. naming the primary key as id (instead of commentid and postid) makes your work easier.

Although you can obtain its primary key by reading the data structure whether or not you access the database Yii, other parts of the system may not do so and they depend on the primary key id.

Example: the default primary key of CArrayDataProvider is id. although you can rewrite its attribute 'keyfield', it is inconvenient to put this attribute first.

Obviously, this will not work when a composite primary key is used, but it is a minority after all.

Avoid special primary key names


A typical design error is that the primary key of the created table has practical significance. in the following column, the user (user) table uses the username as the primary key:

123456 -- Do not do this! Create table user (name VARCHAR (16) primary key, -- bad idea email VARCHAR ......)

This raises two problems: This presents two difficulties:

  1. When elsewhereReferenceBecause it contains 16 characters rather than 4-byte integers. when a large numberReferencePerformance is greatly reduced.

  2. The user wantsModify user nameIt is very difficult: the fields and references in the table must change at the same time, which is expensive.

The best solution is to create an integer field as the primary key and set the name field to unique:

1234567 -- Much betterCREATE TABLE user (id integer primary key AUTO_INCREMENT, name VARCHAR (32) not null unique, email ......);

In this way, only one record is modified when the user updates the user name.

Confirm the foreign key relationships defined in the database structure


Most data supports defining the relationship between tables. fields in one table point to the primary key of another table. These foreign keys help ensure data integrity. when a record executes a record, you cannot delete it.

MySQL InnoDB enforces foreign key constraints, while MyISAM allows youDefinitionBut notForceUse. Yii to know how to deal with these relationships, and use Gii or Giix to automatically generate relationships.

Aside from Yii, foreign keys are an important part of maintaining database integrity. There are many tutorials on the network to learn about them.

Use "id" as the end of the foreign key field


Through the above description, if you have a field pointing to a user, name this field userid instead of user. The reason is that you must defineLink.

Share a namespace in Yii, class variables, data fields, virtual attributes, and relationships, so it is impossible to use the $ model-> user method.At the same timeForeign key used to access the tableAndLink.

You can use the BELONGS_TO relationship in the form of userid, $ model-> user:

12345678 ClassPostextendsCActiveRecord {publicfunctionrelations () {returnarray ('user' => array (self: BELONGS_TO, 'user', 'userid '));}

Note: Many people prefer to replace Id with id or _ id. this is only a matter of personal interests and has the same meaning.

The characteristics of the singular or plural numbers of relational names


To continue, the theme consistency and code are easy to read. The relationship should reflect whether they represent singular or plural in terms of names.

  • HAS_ONE-returns a model ):Singular

  • BELONGS_TO-returns a model ):Singular

  • Has_models-returns an array composed of multiple models:Plural

  • Many_models-returns an array composed of multiple models:Plural

Note: For the relationship that returns an array, they may only contain one model, but in fact they are authenticated by the plural name.Array

You only need to view the link name to know whether it returns an array or a model:

1234 $ Model-> post $ model-> comments $ model-> author $ model-> members

If you only need to view the code, it will make your code more difficult to read and maintain.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.