Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/268.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 在Laravel中查询集合_Php_Laravel_Laravel 5_Eloquent_Laravel Collection - Fatal编程技术网

Php 在Laravel中查询集合

Php 在Laravel中查询集合,php,laravel,laravel-5,eloquent,laravel-collection,Php,Laravel,Laravel 5,Eloquent,Laravel Collection,当我查询Laravel集合时,它不会查询数据库,而是对已经获取的内容执行查询,这一点是否正确 例如,我有一个返回集合的关系: public function permissions() { return $this->belongsToMany(Permission::class, RolePermission::getModelTable(), 'role_id', 'permission_id'); } 下面的代码是查询数据库还是使用php工具处理集合 $role->p

当我查询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()
之间的区别在于,第一个函数返回
集合的一个实例,而第二个函数返回
belongToMany
的一个实例

Collection
是相关对象的集合(真的吗?),而
belongtomany
是关系本身。是的,通过调用方法(而不是magic属性),您可以查询数据库

更新 对不起,我没有回答最后一个问题。 第一次调用
$role->permissions
(magic属性)时,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::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();
正如您所看到的,在第二个示例中,我们要少得多,而且我们也多次执行相同的操作。当然,效率较低

$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();