首页 > 解决方案 > Drupal 8:将节点 ID 从字符串转换为整数

问题描述

根据条件检索节点:

$query = \Drupal::entityQuery('node')
->condition('type', 'my_content_type')
->condition('title', 'my node title');
$nid = $query->execute();

$nid 的结果是正确的节点 ID,但格式是字符串,(es:“123”)

当我想通过它的 ID 加载节点时,我写:

$node_id = Node::load($nid);

这样做,我得到的结果是 NULL,因为变量 $nid 包含一个字符串(不是整数)。如果我这样写代码:

$node_id = Node::load(123);

我加载了节点。

如何将变量字符串 ($nid) 转换为整数?我试过了:

$nid_int = (int) $nid;
$node_id = Node::load($nid_int);

我也试过:

$nid_int = intval($nid);
$node_id = Node::load($nid_int);

但我总是得到结果 NULL

谢谢你的帮助

标签: drupaldrupal-8

解决方案


你不能使用Node::load($nid); 直接,因为$query->execute()返回一个类似['vid' => "nid"]的数组。

$query = \Drupal::entityQuery('node')
->condition('type', 'my_content_type')
->condition('title', 'my node title');
$nids = $query->execute();
$nid = (int)array_shift($nids);

推荐阅读