Laravel 模型关联 「 预加载 」中 with () 方法的功能的示例及说明
laravel 模型关联 「 预加载 」 ->with()功能的示例
1 模型关联说明
:在动态
模型 Status
中,指明一条微博动态属于一个用户 User
<?php
.
.
// 动态模型status 关联belongsTo 用户模型user
class Status extends Model {
public function user() {
return $this->belongsTo(User::class);
}
}
2.不使用
预加载,调用数据时:
// 获取微博动态的发布用户 不使用预加载
$statuses = App\Status::all();
// foreach之前运行 dd($statuses);
foreach ($statuses as $status) {
echo $status->user->name;
}
dd()
打印的结果 ,请注意关注点1
#relations: []为空
LengthAwarePaginator {#319 ▼
#total: 89
#lastPage: 12
#items: Collection {#430 ▼
#items: array:8 [▼
0 => Status {#431 ▶}
1 => Status {#432 ▶}
2 => Status {#438 ▼
#fillable: array:1 [▶]
#connection: "mysql"
#table: "statuses"
.
.
#appends: []
#dispatchesEvents: []
#observables: []
#relations: [] ==============================>>关注点1
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [▶]
}
]
}
.
.
#options: array:2 [▶]
}
3.使用
预加载with('user')
调用数据时:
// 获取微博动态的发布用户 使用预加载 with('user')
$statuses = App\Status::with('user')->get();
// foreach之前运行 dd($statuses);
foreach ($statuses as $status) {
echo $status->user->name;
}
dd()
打印的结果 ,请注意下面标注的 关注点1
#relations: [] 不为空,关注点2
含有对应的user的全部信息
LengthAwarePaginator {#329 ▼
#total: 89
#lastPage: 12
#items: Collection {#425 ▼
#items: array:8 [▼
0 => Status {#432 ▶}
1 => Status {#433 ▶}
2 => Status {#439 ▼
#fillable: array:1 [▶]
#connection: "mysql"
.
.
#dispatchesEvents: []
#observables: []
#relations: array:1 [▼ // =========================>>>>>关注点1
"user" => User {#445 ▼
#fillable: array:3 [▶]
#hidden: array:2 [▶]
#casts: array:1 [▶]
.
.
#attributes: array:11 [▼ // ======================>>>>>关注点2
"id" => 5
"name" => "娄亮"
"email" => "doloribus98@example.com"
"email_verified_at" => "2019-10-05 19:49:31"
"password" => "$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi"
"remember_token" => "N4nrVyeptW"
"created_at" => "2007-07-14 13:34:01"
"updated_at" => "2007-07-14 13:34:01"
"is_admin" => 0
"activation_token" => null
"activated" => 1
]
#original: array:11 [▶]
.
.
#rememberTokenName: "remember_token"
}
]
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [▶]
}
]
}
#options: array:2 [▶]
}
- 对比之后的结论和总结
- 不带
with('user')
方法时,由关注点1
可知 relations[]为空,$statuses 只包动态信息 - 带
with('user')
时,由关注点2
可知,每一个status
都有与其对应
的一个user
属性(含包用户的全部信息) - 重点:预加载方法
with()
的意思就是在foreach 运行获取name之前,已经全部把每一个动态所对应的所有的 name
已经全部准备好了,因此可以有如下结论: - 不带
with('user')
,只有动态信息
,没有动态对应的用户信息,foreach每遍历一次,就要通过 $status->user->name 查询一次数据库。 - 带
with('user')
,拥有动态信息和用户信息
,foreach 只对$statuses遍历,不需要查询数据库。
- 不带
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: