🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
## 聚合模型 >[danger] `5.0.5+`版本一对一关联已经改进,支持关联属性绑定到主模型,以及支持自动关联写入,聚合模型的优势已经不复存在,后面版本不会再更新聚合模型了。 |版本|调整功能| |---|---| |5.0.3|支持使用`field`属性定义需要的字段| |5.0.2|`relationModel` 属性改为非静态定义| 通过聚合模型可以把**一对一关联**的操作更加简化,只需要把你的模型类继承`think\model\Merge`,就可以自动完成关联查询、关联保存和关联删除。 例如下面的用户表关联了档案表,两个表信息如下: ### think_user |字段名 |描述| |---|---| |id|主键| |name|用户名| |password|密码| |nickname|昵称| ### think_profile |字段名 |描述| |---|---| |id|主键| |truename|真实姓名| |phone|电话| |email|邮箱| |user_id|用户ID| 我们只需要定义好主表的模型,例如下面是User模型的定义: ~~~ <?php namespace app\index\model; use think\model\Merge; class User extends Merge { // 定义关联模型列表 protected static $relationModel = ['Profile']; // 定义关联外键 protected $fk = 'user_id'; protected $mapFields = [ // 为混淆字段定义映射 'id' => 'User.id', 'profile_id' => 'Profile.id', ]; } ~~~ >[danger] `V5.0.2+`版本`relationModel` 属性不再使用`static`定义了。 如果需要单独设置关联数据表,可以使用: ~~~ namespace app\index\model; use think\model\Merge; class User extends Merge { // 设置主表名 protected $table = 'think_user'; // 定义关联模型列表 protected static $relationModel = [ // 给关联模型设置数据表 'Profile' => 'think_user_profile', ]; // 定义关联外键 protected $fk = 'user_id'; protected $mapFields = [ // 为混淆字段定义映射 'id' => 'User.id', 'profile_id' => 'Profile.id', ]; } ~~~ >[danger] 注意:对于关联表中存在混淆的字段名一定要通过mapFields属性定义。 接下来,我们可以和使用普通模型一样的方法来操作用户模型及其关联数据。 ~~~ // 关联查询 $user = User::get(1); echo $user->id; echo $user->name; echo $user->phone; echo $user->email; echo $user->profile_id; $user->email = 'thinkphp@qq.com'; // 关联保存 $user->save(); // 关联删除 $user->delete(); // 根据主键关联删除 User::destroy([1,2,3]); ~~~ 操作两个数据表就和操作一个表一样的感觉,关联表的写入、更新和删除自动采用事务(只要数据库支持事务),一旦主表写入失败或者发生异常就会发生回滚。 如果主表除了Profile关联之外,还有其他的一对多关联,一样可以定义额外的关联,例如: ~~~ namespace app\index\model; use think\model\Merge; class User extends Merge { // 定义关联模型列表 protected static $relationModel = ['Profile']; // 定义关联外键 protected $fk = 'user_id'; protected $mapFields = [ // 为混淆字段定义映射 'id' => 'User.id', 'profile_id' => 'Profile.id', ]; public function articles(){ return $this->hasMany('Article'); } } ~~~ 对一对多关联进行操作,例如: ~~~ $user = User::get(1); // 读取关联信息 dump($user->articles); // 或者进行关联预载入 $user = User::get(1,'articles'); ~~~ >[danger] 注意:不能再次对 已经在`relationModel`属性中定义过的关联表进行关联定义和预载入查询。