远层比远程更加好理解吧
相关信息:
- 类型:文档文章
- 文章: 模型关联
- 文档: 《Laravel 5.8 中文文档(5.8)》
此投稿状态为 标记为已读。
内容修改:
Old | New | Differences |
---|---|---|
1 | ||
2 | 1 | # Eloquent: 关联 |
3 | 2 | |
4 | 3 | - [简介](#introduction) | … | … |
8 | 7 | - [一对多 (反向)](#one-to-many-inverse) |
9 | 8 | - [多对多](#many-to-many) |
10 | 9 | - [自定义中间表模型](#defining-custom-intermediate-table-models) |
11 | - [远 | |
12 | - [远 | |
10 | - [远层一对一](#has-one-through) | |
11 | - [远层一对多](#has-many-through) | |
13 | 12 | - [多态关联](#polymorphic-relationships) |
14 | 13 | - [一对一](#one-to-one-polymorphic-relations) |
15 | 14 | - [一对多](#one-to-many-polymorphic-relations) | … | … |
39 | 38 | - [一对一](#one-to-one) |
40 | 39 | - [一对多](#one-to-many) |
41 | 40 | - [多对多](#many-to-many) |
42 | - [远 | |
43 | - [远 | |
41 | - [远层一对一](#has-one-through) | |
42 | - [远层一对多](#has-many-through) | |
44 | 43 | - [一对一 (多态关联)](#one-to-one-polymorphic-relations) |
45 | 44 | - [一对多 (多态关联)](#one-to-many-polymorphic-relations) |
46 | 45 | - [多对多 (多态关联)](#many-to-many-polymorphic-relations) | … | … |
264 | 263 | |
265 | 264 | return $this->belongsToMany('App\Role', 'role_user', 'user_id', 'role_id'); |
266 | 265 | |
267 | ||
266 | ||
268 | 267 | #### 定义反向关联 |
269 | 268 | |
270 | 269 | 要定义多对多的反向关联, 你只需要在关联模型中调用 `belongsToMany` 方法。我们在 `Role` 模型中定义 `users` 方法: | … | … |
407 | 406 | public $incrementing = true; |
408 | 407 | |
409 | 408 | <a name="has-one-through"></a> |
410 | ### 远 | |
411 |
| |
412 | 远 | |
409 | ### 远层一对一关系 | |
410 | ||
411 | 远层一对一关联通过一个中间关联模型实现。 | |
413 | 412 | 例如,如果每个供应商都有一个用户,并且每个用户与一个用户历史记录相关联,那么供应商可以通过用户访问用户的历史记录,让我们看看定义这种关系所需的数据库表: |
414 | 413 | |
415 | 414 | users | … | … |
465 | 464 | } |
466 | 465 | |
467 | 466 | <a name="has-many-through"></a> |
468 | ### 远 | |
469 |
| |
470 | 远 | |
467 | ### 远层一对多关联 | |
468 | ||
469 | 远层一对多关联提供了方便、简短的方式通过中间的关联来获得远层的关联。例如,一个 `Country` 模型可以通过中间的 `User` 模型获得多个 `Post` 模型。在这个例子中,你可以轻易地收集给定国家的所有博客文章。让我们来看看定义这种关联所需的数据表: | |
471 | 470 | |
472 | 471 | countries |
473 | 472 | id - integer | … | … |
523 | 522 | } |
524 | 523 | } |
525 | 524 | |
526 | ||
525 | ||
527 | 526 | |
528 | 527 | <a name="polymorphic-relationships"></a> |
529 | 528 | ## 多态关联 | … | … |
847 | 846 | |
848 | 847 | 动态忔是「懒加载」的,这意味着它们仅在你真实访问关联数据时才被载入。因此,开发者经常使用 [预加载](#eager-loading) 预先加载那些他们确知在载入模型后将访问的关联。对载入模型关联中必定被执行的 SQL 查询而言,预加载显著减少了查询的执行次数。 |
849 | 848 | |
850 | ||
849 | ||
851 | 850 | |
852 | 851 | <a name="querying-relationship-existence"></a> |
853 | 852 | ### 查询已存在的关联 | … | … |
1028 | 1027 | |
1029 | 1028 | > {note} 在约束预加载时,不能使用 `limit` 和 `take` 查询构造器方法。 |
1030 | 1029 | |
1031 | ||
1030 | ||
1032 | 1031 | <a name="lazy-eager-loading"></a> |
1033 | 1032 | ### 预加载 |
1034 | 1033 | … | … |
1275 | 1274 | |
1276 | 1275 | $user = App\User::find(1); |
1277 | 1276 | |
1278 | $user->roles()->updateExistingPivot($roleId, $attributes); | |
1277 | $user->roles()->updateExistingPivot($roleId, $attributes); | |
1279 | 1278 | |
1280 | 1279 | <a name="touching-parent-timestamps"></a> |
1281 | 1280 | ## 更新父级时间戳 |