Model for meta table in Yii
I just started developing my new project in Yii, I开发者_如何学JAVA am new to Yii as well as to frameworks ans MVC structure.
I would to get some advice on making meta tables and model for that table. Suppose I like to store several chat handles for a user. I have created a table to store the user details like user_id, user_name, email.. and another table which is my meta table with structure id, user_id, key, value
I would like to associate these two tables in one model so that I can access the value of key stored in the meta table like $user->yahoo.
Thanks in advance.
Simply create a model for the meta table as well as the primary table. Then if you have a forign key relation to this table you will be able to access the meta table model as a property of the primary table. To make thigs clearer:
Say we have these two tables:
Customer -id -name -address -name -email
customer_meta -id -customer_id -meta_key -meta_value
you would generate two models using Gii for both of these tables. Then if you use MySQL and InnoDB tables and create a foriegn key relation ebtween customer.id -> customer_meta.customer_id you will be able to access the meta data in the customer model as such:
// this will echo get the first meta value
$model = new customer;
$customer = $model->loadModel( 3 );
echo $customer->customer_meta[0]->meta_value;
// or loop through the meta data
foreach( $customer->customer_meta as $meta ) {
echo 'Name: '.$meta->meta_key.' Value: '.$meta->meta_key.'<br />';
}
see: http://www.yiiframework.com/doc/guide/1.1/en/database.arr
It walks you through a basic example similar to what you want to do. Note that if you set up your database with foreign keys, the Gii tools will create this relation for you in your model. If you are using MySql, MySqlWorkbench or other similar tools can be helpful for managing foreign keys, you just need to make sure you are using InnoDB type tables.
use getters and setters. Define a getYahoo method and in that method do de lookup table to retrieve the value that you want
精彩评论