How to create Relations automatic

Hi dears,

Is there any way that Gii creates Relations between the tables automatically?

Thanks

I think when you have these relations defined at database level, Gii will create models with relevant relations.

Let’s imagine that you have table1 with columns id, name and id_user and table2 with columns id and username.

If you defined table1.user_id as FOREIGN KEY to table2.id (which is PRIMARY KEY) then you will get in model rules:




/**

 * @return array relational rules.

 */

public function relations()

{

// NOTE: you may need to adjust the relation name and the related

// class name for the relations automatically generated below.

return array(

	'table1_relation' => array(self::BELONGS_TO, 'table2', 'user_id'),

);

}

Yes, do it at the database level first. Then use Gii.

Requires InnoDb if using MySql, but I guess you can change it back if you don’t like/need Inno…

I believe that it will also pick up the relationships from a MyISAM table as well if you define the foreign key relationship via comment on the table.

Found the link where it discusses using COMMENT to create the relationship note just for Yii’s benefit:

http://www.yiiframework.com/doc/guide/1.0/en/database.arr

Dana thanks for your helpful reply.

I will try it.

pc131,

dear, I have tables as

categories.category_id

and

product.product_id

product.category_id

When I creates the model, it does not create the relation automatically.

jacmoe thanks dear

I have one more question which is seems to be odd.

To use the relations, have we to declare in each of the model of the table?

For example,

users and profile table are inter related, then have we to define it as

in user model

user has many profiles

and in profile model

profile has one user

thanks

Yes, you’re going to want to have it defined in both.

Nope! it doesn’t. Currently working on a new project and forced me to change it to InnoDB <Usually you choose between Inno or MyISAM depending if you do lots of transactions (commit, rollbacks etc) or data manipulation or data selection and display. I did the change not to type less but cuz of the nature of the project, writing a couple of lines more wont hurt anyone>

:)

thanks dana

I’ve just tried what Dana suggested and it worked like a charm (using comments). Thanks Dana B)

I’m using Yii v1.1.6 and MySQL (MyISAM type).

Cheers

The solution Dana suggests works.

Except there is a problem for versions of MySQL lower than 6.

The version of MySQL (MyISAM) that I am using has table comments limited to 60 characters.

So if you need to define lots of relations then the comment field quickly becomes full/truncated.

Is there any other way of defining relations autmatically when the model is created?

(When using MySQL & the MyISAM engine)

Thanks,

Rick.