Now that we have our MySQL connection set up, it's time to use it.
The way the Yii Framework works with data is you create 'Models' which define the relations, rules, and other properties. As of Yii 1.0.6 there is a new feature that will create all of your models with one command and if you have your foreign keys set up it will automatically create your table relations for you.
If you're unfamiliar with foreign keys, basically what they do is say this field should match another table's key.
So first we'll go ahead and set up our database.
We're going to keep this really simple just for demonstration purposes.
We'll create 4 tables. They will be:
Brand
Product
Category
ProductCategory
We will set three foreign key relationships.
Product.brandId => Brand.id ProductCategory.productId => Product.id ProductCategory.categoryId => Category.id
One important thing to not is that not all storage engines support foreign keys, so you need to use one that does. InnoDB does support foreign keys, so that is the engine I will be using.
Click Here To Download My Sample DB Dump.
If you want to follow along, go ahead and download and load up your database using the dump provided above.
Now we're going to create our models.
The Yii Framework comes with a shell command that is really great, and will generate your models for you.
Now let's open up our terminal and let yii's shell script generate our models for us.
cd /data/web/vhosts/mysqltest.com/protected ./yiic shell ../index.php [This is running the yii shell using the configuration from your main index file] model * [This will tell you what models it will set up for you. Go ahead and confirm it.]
If everything works properly you should now have some new classes in your protected/models folder which we will be using in the next micro-tutorial.

8 comments to "Yii Framework + MySQL Part 2 (Creating Models)"
I've updated the sample dump code. :) Shame on you phpMyAdmin SQL Dump!
Leave a Comment