#### 本文测试关联方法都采用预载入查询 ```php $data = User::with('profile')->select(); halt($data->toArray()); ``` #### 1. 创建数据表 --- ![](https://img.itqaq.com/art/content/7693feb167fda4dbaaf2dda3f6f5b9cb.png) ```sql -- 用户表 DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '用户id', `username` varchar(255) NOT NULL COMMENT '用户名', `password` char(32) DEFAULT NULL COMMENT '登陆密码', PRIMARY KEY (`id`) USING BTREE ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COMMENT='用户表'; INSERT INTO `user` VALUES (1, 'liang', 'e10adc3949ba59abbe56e057f20f883e'); INSERT INTO `user` VALUES (2, 'zhangsan', 'e10adc3949ba59abbe56e057f20f883e'); INSERT INTO `user` VALUES (3, 'laowang', 'e10adc3949ba59abbe56e057f20f883e'); INSERT INTO `user` VALUES (4, 'wangwu', 'e10adc3949ba59abbe56e057f20f883e'); INSERT INTO `user` VALUES (5, 'xiaosun', 'e10adc3949ba59abbe56e057f20f883e'); -- 用户资料表 DROP TABLE IF EXISTS `profile`; CREATE TABLE `profile` ( `user_id` int(11) DEFAULT NULL COMMENT '用户id', `age` tinyint(4) DEFAULT NULL COMMENT '年龄', `mobile` bigint(20) DEFAULT NULL COMMENT '手机号', `gender` char(1) DEFAULT NULL COMMENT '性别' ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用户资料表'; INSERT INTO `profile` VALUES (1, 20, 12305, '男'); INSERT INTO `profile` VALUES (2, 30, 10086, '女'); INSERT INTO `profile` VALUES (5, 40, 10010, '男'); ``` #### 2. 用户模型定义一对一关联方法 --- ```php public function profile() { // hasOne('关联模型类名', '外键', '主键'); // 用户资料表的外键字段 user_id, 默认为当前模型名 + _id // 用户表的主键字段 id, 默认为当前模型主键 $pk 属性的值 return $this->hasOne(Profile::class, 'user_id', 'id'); } ``` ![](https://img.itqaq.com/art/content/ceaa9e36d6754d8587e0bef46b94d966.png) #### 3. 一对一关联支持额外的方法 --- **一、bind():绑定关联表的属性到父模型属性** ```php public function profile() { return $this->hasOne(Profile::class, 'user_id', 'id') // bind(['字段', '别名' => '字段']) ->bind(['age', 'new_mobile' => 'mobile']); } ``` ![](https://img.itqaq.com/art/content/e8ee1358aadb5fbfb864b86f4fab9a53.png) **二、其他方法** ```php public function profile() { return $this->hasOne(Profile::class, 'user_id', 'id') // 追加获取器 ->append(['checked']) // 隐藏关联表的属性 ->hidden(['age']); } ``` ![](https://img.itqaq.com/art/content/974eb996370715eaba2a84f1f6c0026d.png)