Yii2 Gii How to tell if a relationship is a one-to-one or one-to-many

Hello community!

I’m working on modifying the Gii code to autogenerate some special views for our company project template. I’ve come across a problem I haven’t been able to resolve. How can I determine if the relationship between to tables is a One-To-One or a One-To-Many?

I snooped at the code from the model Generator class, and found out that @Quian Xue implemented a isHasManyRelation function that seems by the name that it does something similar, however my work is in the CRUD generator class. I tried to copy the code to the crud generator class and adapt it, but haven’t been able to make it work, probably because I don’t understand how it works.

If anyone has knowledge of how can this be accomplished I would appreciate it. Btw, I also looked at the db\Schema and db\TableSchema classes looking for some quick method to do this but apparently they dont have one.


I dont know how it is done in the Yii code, but i think an algorithm would be something like this:

  • [size=2]When [i]tableA,id /i is related to tableB.some_field (unique) we have a 1->1 relationship. [/size]
  • [size=2]When tableA,id (pk) is related to tableB.some_field ([/size]not[size=2] unique) we have a 1->* relationship.[/size]

Maybe you can use some Schema methods to verify these possibilities (or some variation of them).


Thank you for your reply. I think that points into the right direction. I will study that and post anything I find (good or bad). Thanks.

Glad to hear you, Rullan. You are welcome.


I’ve been looking into your approach but I have a couple of doubts. For example, the tables shown in this image:

translate into this sql schema,


I see no connection between the relationship as described in the SQL code to that described in the model, which is explicitly declared as one-to-one.

Also note that the foreign key role_id is not declared as Unique, at least not necessarily, however the Gii generator still identifies it as Role->hasOne Parent, while the parent_id is identified as Parent->hasMany Child. Any ideas?


Solved the problem, thanks to slinstj who turned me into the right direction! Turns out that to be able to create a one-to-one relationship it is “mandatory” that the foreign key column used to reference the other table’s primary key be unique.

The code in the Gii Model Generator works as long as the column is unique. Somehow I thought it wasn’t required but as soon as I added the unique index to the column, the code worked like a charm. I had to Alter the table to add this unique index and also had to update the model in Yii.

Also this link helped: http://www.databasejournal.com/features/mysql/article.php/3906761/Cardinality-in-MySQL-Data-Modeling.htm