🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
## 一对一关联 定义一对一关联,例如,一个用户都有一个个人资料,我们定义User 模型如下: ~~~ namespace app\index\model; use think\Model; class User extends Model { public function profile() { return $this->hasOne('Profile')->field('id,name,email'); } } ~~~ **关联查找** 定义好关联之后,就可以使用下面的方法获取关联数据: ~~~ $user = User::find(1); // 输出Profile关联模型的email属性 echo $user->profile->email; ~~~ 默认情况下, 我们使用的是user_id 作为外键关联,如果不是的话则需要在关联定义的时候指定,例如: ~~~ namespace app\index\model; use think\Model; class User extends Model { public function profile() { return $this->hasOne('Profile','uid'); } } ~~~ **关联新增** ~~~ $user = User::find(1); // 如果还没有关联数据 则进行新增 $user->profile()->save(['email' => 'thinkphp']); ~~~ 系统会自动把当前模型的主键传入profile模型。 **关联更新** 和新增一样使用save 方法进行更新关联数据。 ~~~ $user = User::find(1); $user->profile->email = 'thinkphp'; $user->profile->save(); // 或者 $user->profile->save(['email' => 'thinkphp']); ~~~ **定义相对的关联** 我们可以在Profile 模型中定义一个相对的关联关系,例如: ~~~ namespace app\index\model; use think\Model; class Profile extends Model { public function user() 一对一关联 本文档使用 看云 构建 - 266 - { return $this->belongsTo('User'); } } ~~~ belongsTo 的参数包括: **belongsTo('关联模型名','外键名','关联表主键名',['模型别名定义'],'join类型');** 默认的关联外键是user_id ,如果不是,需要在第二个参数定义 ~~~ namespace app\index\model; use think\Model; class Profile extends Model { public function user() { return $this->belongsTo('User','uid'); } } ~~~ 我们就可以根据档案资料来获取用户模型的信息 ~~~ $profile = Profile::find(1); // 输出User关联模型的属性 echo $profile->user->account; ~~~