#### 本文測試關(guān)聯(lián)方法都采用預(yù)載入查詢 ```php $data = User::with('profile')->select(); halt($data->toArray()); ``` #### 1. 創(chuàng)建數(shù)據(jù)表 --- ![](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. 用戶模型定義一對一關(guān)聯(lián)方法 --- ```php public function profile() { // hasOne('關(guān)聯(lián)模型類名', '外鍵', '主鍵'); // 用戶資料表的外鍵字段 user_id, 默認(rèn)為當(dāng)前模型名 + _id // 用戶表的主鍵字段 id, 默認(rèn)為當(dāng)前模型主鍵 $pk 屬性的值 return $this->hasOne(Profile::class, 'user_id', 'id'); } ``` ![](https://img.itqaq.com/art/content/ceaa9e36d6754d8587e0bef46b94d966.png) #### 3. 一對一關(guān)聯(lián)支持額外的方法 --- **一、bind():綁定關(guān)聯(lián)表的屬性到父模型屬性** ```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']) // 隱藏關(guān)聯(lián)表的屬性 ->hidden(['age']); } ``` ![](https://img.itqaq.com/art/content/974eb996370715eaba2a84f1f6c0026d.png)