企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
## 附加一个关联模型 您常常会需要加入新的关联模型。例如新增一个 comment 到 post 。除了手动设定模型的 post_id 外键,也可以从上层的 Post 模型新增关联的 comment : ~~~ $comment = new Comment(['message' => 'A new comment.']); $post = Post::find(1); $comment = $post->comments()->save($comment); ~~~ 上面的例子里,新增的 comment 模型中 post_id 字段会被自动设定。 如果想要同时新增很多关联模型: ~~~ $comments = [ new Comment(['message' => 'A new comment.']), new Comment(['message' => 'Another comment.']), new Comment(['message' => 'The latest comment.']) ]; $post = Post::find(1); $post->comments()->saveMany($comments); ~~~ ## 从属关联模型 ( Belongs To ) 要更新 belongsTo 关联时,可以使用 associate 方法。这个方法会设定子模型的外键: ~~~ $account = Account::find(10); $user->account()->associate($account); $user->save(); ~~~ ## 新增多对多关联模型 ( Many To Many ) 您也可以新增多对多的关联模型。让我们继续使用 User 和 Role 模型作为例子。我们可以使用 attach 方法简单地把 roles 附加给一个 user: #### 附加多对多模型 ~~~ $user = User::find(1); $user->roles()->attach(1); ~~~ 也可以传入要存在枢纽表中的属性数组: ~~~ $user->roles()->attach(1, ['expires' => $expires]); ~~~ 当然,有 attach 方法就会有相反的 detach 方法: ~~~ $user->roles()->detach(1); ~~~ attach 和 detach 都可以接受ID数组作为参数: ~~~ $user = User::find(1); $user->roles()->detach([1, 2, 3]); $user->roles()->attach([1 => ['attribute1' => 'value1'], 2, 3]); ~~~ #### 使用 Sync 方法同时附加一个以上多对多关联 您也可以使用 sync 方法附加关联模型。 sync 方法会把根据 ID 数组把关联存到枢纽表。附加完关联后,枢纽表里的模型只会关联到 ID 数组里的 id : ~~~ $user->roles()->sync([1, 2, 3]); ~~~ #### Sync 时在枢纽表加入额外数据 也可以在把每个 ID 加入枢纽表时,加入其他字段的数据: ~~~ $user->roles()->sync([1 => ['expires' => true]]); ~~~ 有时您可能想要使用一个命令,在建立新模型数据的同时附加关联。可以使用 save 方法达成目的: ~~~ $role = new Role(['name' => 'Editor']); User::find(1)->roles()->save($role); ~~~ 上面的例子里,新的 Role 模型对象会在储存的同时关联到 user 模型。也可以传入属性数组把数据加到关联数据库表: ~~~ User::find(1)->roles()->save($role, ['expires' => $expires]); ~~~