Search code examples
phpdatabasemodelyiirelational

Model for meta table in Yii


I just started developing my new project in Yii, I 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.


Solution

  • 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 />';
    }