我是否正确地知道当我查询Laravel集合时,它不查询数据库而是对已经获取的内容执行查询?
例如,我有一个返回集合的关系:
public function permissions()
{
return $this->belongsToMany(Permission::class, RolePermission::getModelTable(), 'role_id', 'permission_id');
}
以下代码是否查询数据库或使用php工具与集合一起使用?
$role->permissions->where('code','global.test')->count()
而且,据我了解,如果我查询关系,则将查询数据库,而不是处理已经获取的结果:
$role->permissions()->where('code','global.test')->count()
因此,基本上,$ role-> permissions-使用获取的结果“脱机”,但是$ role-> permissions() -查询数据库
哪种方法通常更有效?何时?
你基本上是对的。$role->permissions
和之间的区别$role->permissions()
是,第一个返回的实例Collection
,而第二个返回的实例BelongsToMany
。
Collection
是相关对象的集合(真的吗?),并且BelongsToMany
是关系本身。因此,是的,通过调用方法(而不是magic属性)可以查询数据库。
我没有最后一个问题,对不起。第一次调用$role->permissions
(魔术属性)时,Laravel将获取与之关联的所有权限$role
(如果它们不急于加载)。如果只需要这些权限的一部分,则可以使用任何magic属性和方法对其进行过滤。让我举一些例子。
$role = Role::first();
// Fetch all the permissions and count a subset.
$role->permissions->where('code', 'global.test')->count();
// Count another subset.
$role->permissions->where('code', 'another.test')->count();
可以使用以下方法完成此操作:
$role = Role::first();
// Fetch a subset of the permissions and count it.
$role->permissions()->where('code', 'global.test')->count();
// Fetch another subset and count it.
$role->permissions()->where('code', 'another.test')->count();
如您所见,在第一个示例中,您仅执行一个查询并以不同的方式过滤结果。在第二个示例中,您将进行两个查询。第一个显然更有效。
但是,如果在同一执行过程中仅需要一个子集,则情况会发生变化。在这里,我们正在使用紧急加载:
$role = Role::with('permissions', function($query) {
// Here we filter the related permissions.
$query->where('code', 'global.test');
})->first();
// We have what we want. No need to filter the collection.
$role->permissions->count();
// Let's do something else with this subset.
$role->permissions->all();
如果获取所有相关对象,但只需要该子集,该怎么办?
$role = Role::first();
// Filter the collection to count the needed subset.
$role->permissions->where('code', 'global.test')->count();
// Filter the collection to get the needed subset.
$role->permissions->where('code', 'global.test')->all();
如您所见,在第二个示例中,我们少了DRY,而且我们也多次执行相同的操作。当然,效率较低。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句