您好,欢迎访问一九零五行业门户网

yii的relations要怎么写?熟悉YII的朋友们帮看看

表一  (city)
id    name   code
1     北京     0001
2     上海     0002
表二 (user)
id    username  citycode
1      小李        0001
2      小王        0001
3      小红        0002
第二个表的citycode字段是第一个表的code字段相对应
在yii的model里要怎么写这两个model的relations要怎么写呢?
city表的对应model  (city.php)
array(self::has_many, 'user', 'code'),这里不知道要怎么写,这样写不知道对不对? ); }//…………}
user表的对应model (user.php)
array(self::belongs_to, 'city', 'citycode'),这里不知道要怎么写,这样写不知道对不对? ); }//…………}
按我上面的写法,在视图(view)文件里 使用如:$data->city->name  或 $data->user->username会出错。
初学yii 对relation不知道要怎么写,麻烦知道的朋友指导下,谢谢了!
回复讨论(解决方案) 没人帮解决吗?
我也是个新手,说说我的看法!
首先你的表就有问题,作为两个表产生 关联是因为有 外键约束。而你的第一个表中的字段 citycode不是主键,那么就不能作为外键。就谈不上,两个表之间的联系了。
如果,你的表创建如下:
create table city(
    citycode varchar(25) not null primary key,
    name varchar(128) not null,
);
create table user(
    id int(11) primary key,
     name varchar(128) not null,
    citycode varchar(25) not null,
    foreign key(citycode) references city(citycode),
);
建立了外键之后,
描述 关联关系:
user 中:
return array('user'=>array(self::belongs_to, 'city', 'citycode'));
city中:
return array('city'=>array(self::has_many, 'user', 'citycode'));
其它类似信息

推荐信息