返回

msgraph-sdk-php v2 中使用 Skiptoken 获取更多结果:分步指南

php

在 msgraph-sdk-php v2 中使用 Skiptoken 获取更多结果

问题背景

Microsoft Graph 是访问 Microsoft 365 数据和服务的 API,可以用来获取用户、邮件和其他信息。当从 Microsoft Graph 获取数据时,默认只返回最多 100 条结果。为了获取更多结果,需要使用 $skiptoken 参数进行增量查询。

解决方案

在 msgraph-sdk-php v2 中传递 $skiptoken 的步骤如下:

  1. **获取 nextLink 值:** `response对象的getOdataNextLink方法返回一个包含skiptoken` 参数的 URL,称为 `nextLink`。

  2. **修改 nextLink 值:** 将 `nextLink值中的?skiptoken=替换为&$skiptoken=`。例如:

$nextLink = 'https://graph.microsoft.com/v1.0/users?$skiptoken=100';
$nextLink = str_replace('?skiptoken=', '&$skiptoken=', $nextLink);
  1. **将修改后的 nextLink 值传递给 get 方法:** 在 `get` 方法中使用 `queryParameters` 参数传递修改后的 `nextLink` 值。例如:
$request = new UsersRequestBuilderGetRequestConfiguration();
$request->queryParameters = UsersRequestBuilderGetRequestConfiguration::createQueryParameters();
$request->queryParameters->expand = array('skiptoken' => $nextLink);
$response = $o365->users()->get($request)->wait();

代码示例

以下是一个代码示例,演示了如何在实际应用中使用 $skiptoken

use Microsoft\Graph\Graph;
use Microsoft\Graph\Model\User;

// 创建 Graph 客户端
$graph = new Graph();

// 获取第一个结果集
$users = $graph->users()->get()->wait();

// 检查是否有更多结果
if ($nextLink = $users->getOdataNextLink()) {
    // 修改 $nextLink 值
    $nextLink = str_replace('?skiptoken=', '&$skiptoken=', $nextLink);

    // 获取下一个结果集
    $users = $graph->users()->get()->queryParameters(['$expand' => 'skiptoken=' . $nextLink])->wait();
}

常见问题解答

1. 什么是增量查询?

增量查询是一种查询技术,允许分批获取结果,避免一次性加载大量数据。

2. 如何确定何时需要使用 skiptoken?

当从 Microsoft Graph 获取的结果超过 100 条时,需要使用 $skiptoken

3. skiptoken 参数有什么限制?

$skiptoken 参数值的最大长度为 8 KB。

4. 是否可以跳过指定数量的结果?

不能直接跳过指定数量的结果。$skiptoken 参数仅允许顺序获取结果。

5. 是否可以在其他 Microsoft Graph 请求中使用 skiptoken?

是的,$skiptoken 参数也可以在其他支持增量查询的 Microsoft Graph 请求中使用。