Professional Documents
Culture Documents
DO name your database tables in the singular, not plural DON'T prepend db table names to field names DON'T include a table prefix in the model class name DO name a table's own ID column "id" AVOID semantically-meaningful primary key names DO define foreign-key relationships in the database schema DO name your foreign key fields ending in "id" DO name relations to reflect their singular/plural nature
Virtually all Yii applications are built on top of a database, and though Yii is very flexible in how it addresses your DB, some design choices make things more convenient than others. First, and most broadly, because Yii applications use ActiveRecord so heavily, design considerations revolve around optimization for that use, rather than for a human who will be composing complex SQL queries. In fact, many of these design notes are directly in conflict to best practices for creating SQL-friendly schemas. But much of this is about creating code that can be read and understood by others, where naming conveys meaning, but where inconsistent conventions will make it much harder to follow. This is especially the case if you're asking for help in the forums or in the #yii channel: using odd names that don't reflect good meaning gets you a lot more questions clarifying what the code is doing, and sometimes less help about your actual problem.
Consistency matters a lot. However, these are only guidelines, not rules, and your code will work if they're not followed. But you'll have an easier path if you adopt them.
Call your table comment not comments, invoice not invoices, and so on, and reflect the model class names as well (Comment, Invoice, etc.) If you absolutely cannot change the db schema, at least change the Yii model class name to reflect the proper case, but make an extra //COMMENT in the code to remind the user of this mismatch.
value INTEGER
Doing it the "long" way does make hand-crafted SQL queries a bit easier to read, but use in ActiveRecord less convenient.
-- bad idea
Far better is to create an integral primary key and make the name unique:
-- much better CREATE TABLE user ( id INTEGER PRIMARY KEY AUTO_INCREMENT, name VARCHAR(32) NOT NULL UNIQUE, email ... ...);
This way, changing the person's username involves updating just this one record.
2
HAS_ONE - returns a single model: singular BELONGS_TO - returns a single model: singular HAS_MANY - returns an array of models: plural MANY_MANY - returns an array of models: plural
Note that for relations returning an array, they might have only one model, but the fact that they're an array is what warrants the plural name. You should always be able to tell just by looking whether a relation returns an array or a model: $model->post $model->comments $model->author $model->members If you have to look it up, it makes the code much more difficult to read and maintain.