yii模型中关系(relations)中非主键关联的解决方案
来源:互联网 发布:淘宝花相公美妆真假 编辑:程序博客网 时间:2024/04/28 11:19
显示A表的记录,该表与B表如果通过主键关联,一对一的关系如下:
/** * @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('myauthitem'=>array(self::HAS_ONE,'AuthItem','userid'),);}
其中userid是AuthItem模型所对应表中的关联字段。YII默认是用主表的主键与该字段(userid)关联。可打开CWebLogRoute看一下,摘要如下:
Querying SQL: SELECT `t`.`id` AS `t0_c0`, `t`.`username` AS `t0_c1`,`t`.`password` AS `t0_c2`, `t`.`role` AS `t0_c3`, `t`.`description` AS`t0_c4`, `t`.`last_login_time` AS `t0_c5`, `t`.`last_login_ip` AS `t0_c6`,`myauthitem`.`name` AS `t1_c0`, `myauthitem`.`type` AS `t1_c1`,`myauthitem`.`description` AS `t1_c2`, `myauthitem`.`bizrule` AS `t1_c3`,`myauthitem`.`data` AS `t1_c4` FROM `kj_manager` `t` LEFT OUTER JOIN`kj_authitem` `myauthitem` ON (`myauthitem`.`userid`=`t`.`id`) LIMIT 10
但是,如果A表的非主键如何解决这个问题。
比如管理员表,字段为id,name,password,role,time....,role字段为“角色”属性,关联Authitem表的name字段,显示description信息。
可通过以下方案解决:
/** * @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('myauthitem'=>array(self::HAS_ONE,'AuthItem','','on'=>'t.role=myauthitem.name'),);}‘on’: the ON clause. The condition specified here will be appended to the joining condition using the AND operator.
on子句,通过 and 操作符附加到join条件之后。
因此,relations关系中,如果没有主键关联,则第三个参数必须设置为空。
查看一下生成的SQL:
Querying SQL: SELECT `t`.`id` AS `t0_c0`, `t`.`username` AS `t0_c1`,`t`.`password` AS `t0_c2`, `t`.`role` AS `t0_c3`, `t`.`description` AS`t0_c4`, `t`.`last_login_time` AS `t0_c5`, `t`.`last_login_ip` AS `t0_c6`,`myauthitem`.`name` AS `t1_c0`, `myauthitem`.`type` AS `t1_c1`,`myauthitem`.`description` AS `t1_c2`, `myauthitem`.`bizrule` AS `t1_c3`,`myauthitem`.`data` AS `t1_c4` FROM `kj_manager` `t` LEFT OUTER JOIN`kj_authitem` `myauthitem` ON (t.role=myauthitem.name) LIMIT 10
- yii模型中关系(relations)中非主键关联的解决方案
- Yii中relations的用法
- yii的relations默认是用当前指定的键跟关联表的主键进行join
- Yii 多表关联relations
- Yii 多表关联relations
- 关于yii的relations
- 关于yii的relations
- 关于yii的relations
- Yii - relations数据关联中的统计功能
- Yii - relations数据关联中的统计功能
- yii relations 两表关联查询
- YII使用relations关联聚合指定字段
- yii关系relations之HAS_MANY之排序
- Yii框架relations的使用
- Yii model 中使用表与表之间关联运用(relations)
- Yii框架中ActiveRecord使用Relations
- 基于主键的一对一关联关系
- 基于复合主键的关联关系
- c语言课程总结
- Android的自动测试研究--Robotium
- 五大常用算法——分治算法
- gbs remotebuild使用说明
- Struct 中字节对齐问题
- yii模型中关系(relations)中非主键关联的解决方案
- visuall assist x 破解方法
- 总结:复合数据对象
- raid信息存放位置
- 五大常用算法——动态规划
- Android 数据Parcel序列化过程源码分析
- java socket 传输文件
- Android动画学习笔记-Android Animation
- 五大常用算法——贪心算法