drupal - 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
谢谢你的帮助
解决方案
你不能使用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);
推荐阅读
- android - 加载 HLS 播放列表时 Android WebView 崩溃
- python - 如何为管道难题实施 AI python 解决方案
- tableau-api - 在 Tableau 中计算两个日期的两个百分比之间的百分比差异
- assembly - 我需要对一个字符串(AZ)进行桶排序并在汇编中打印它
- java - 如何在服务上获取 websocket 会话?
- google-sheets - 总和在 arrayformula 旁边的列中不起作用
- javascript - 尝试使用 JS 将 JSON 发布到 PHP 时出现错误 404
- python - 创建一个列,该列是从另一列中提取的特定日期之后的一组列中的日期数的总和
- swift - 在路径 SwiftLint 中找不到可删除的文件
- zsh - zsh条件表达式中的-a和-e有什么区别?