企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
> ### 定义一对一关联 > 描述:一个用户有一份资料 > ## hasOne('关联的模型', '外键名', '主键名', 'join类型') > 有一点需要注意的是,关联方法的命名规范是驼峰法,而关联属性则一般是小写+下划线的方式,系统在获取的时候会自动转换对应,读取user_profile关联属性则对应的关联方法应该是userProfile。 ``` // 模型中这样定义 class User extends Model { // 一个User有一个Profile public function profile() { // 定义关联(默认使用user_id作为外键进行关联) return $this->hasOne('Profile'); // 如果外键为uid,则需要如此设置 return $this->hasOne('Profile','uid'); // 指定关联的字段 // 如果使用的是join方式的关联,不支持指定field字段 return $this->hasOne('Profile')->field('id,name,email'); // 绑定指定的字段到父模型(支持读取器) return $this->hasOne('Profile','uid')->bind('nickname,email'); // 还可以给绑定到父模型的子模型字段指定别名 return $this->hasOne('Profile','uid')->bind([ 'email', 'truename' => 'nickname', 'profile_id' => 'id', ]); // 这样可以直接在控制器这样访问 $user = User::get(1,'profile'); // 输出Profile关联模型的email属性 echo $user->email; echo $user->profile_id; } } ``` > ### 关联查找 ``` // 获取关联的属性 $user = User::get(1); echo $user->profile->email; // 获取指定条件的关联属性 $user = User::hasWhere('profile',['email'=>'thinkphp@qq.com'])->find(); echo $user->name; ``` > ### 关联新增 ``` $user = User::get(1); // 如果还没有关联数据 则进行新增 $user->profile()->save(['email' => 'thinkphp']); // 动态新增属性 $user = User::find(1); $user->profile->phone = '1234567890'; $user->profile->save(); ``` > ### 关联更新 ``` $$user = User::get(1); $user->profile->email = 'thinkphp'; $user->profile->save(); // 或者 $user->profile->save(['email' => 'thinkphp']); ``` > ## 定义反向关联 > ### belongsTo('关联模型名','外键名','关联表主键名',['模型别名定义'],'join类型'); ``` // Profile属于User class Profile extends Model { public function user() { // 默认关联的外键为user_id return $this->belongsTo('User'); // 如果需要指定关联的外键 return $this->belongsTo('User','uid'); } } // 根据子模型获取父模型的数据 profile = Profile::get(1); // 输出User关联模型的属性 echo $profile->user->account; ``` > ### 关联自动写入更新和删除 ``` // 关联插入 $blog = new Blog; $blog->name = 'thinkphp'; $content = new Content; $content->data = '实例内容'; $blog->content = $content; $blog->together('content')->save(); // 关联更新(同时更新当前模型与其关联模型) $blog = Blog::get(1); $blog->title = '更改标题'; $blog->content->data = '更新内容'; $blog->together('content')->save(); // 关联删除 $blog = Blog::get(1); $blog->together('content')->delete(); ```