Gii CRUD generator and related tables

2.5k views Asked by At

I am using Yii framework and I have got a problem with CRUD generator. I have got two tables called Users and news with the following structures:

CREATE TABLE IF NOT EXISTS `news` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `keyword` varchar(1000) COLLATE utf8_persian_ci DEFAULT NULL,
  `user_id` tinyint(3) unsigned NOT NULL,
  `title` varchar(100) COLLATE utf8_persian_ci DEFAULT NULL,
  `body` varchar(1000) COLLATE utf8_persian_ci DEFAULT NULL,
  `publishedat` date DEFAULT NULL,
  `state` tinyint(1) unsigned DEFAULT NULL,
  `archive` tinyint(1) unsigned DEFAULT NULL,
  `last_modified` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `news_FKIndex1` (`keyword`(255)),
  KEY `news_FKIndex2` (`user_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_persian_ci AUTO_INCREMENT=3 ;




CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(20) NOT NULL,
  `password` varchar(128) NOT NULL,
  `create_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `lastvisit_at` timestamp NULL DEFAULT NULL,
  `is_disabled` tinyint(1) NOT NULL DEFAULT '1',
  PRIMARY KEY (`id`),
  UNIQUE KEY `username` (`username`),
  KEY `status` (`is_disabled`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=7 ;

when I generate a CRUD using Gii for my news table I cannot see the fields for users table. Instead of user_id I want to see the username in the table created by CRUD generator. How can I make a change in the code to get the result as above?

1

There are 1 answers

1
topher On

First, user_id needs to be a foreign key field not just a key field.

Second, gii will not generate the field as you require by default. For such functionality an extension such as Giix might help. However, since a relation exists you could always use relationName.username to display the username in a grid view or a list view.