Drupal 8 - 获取带有 Url 别名一部分的所有节点

4
我尝试找到一种方法,通过节点的URL别名的一部分来获取所有节点。 我知道可以通过完整的URL别名获取特定节点。例如:
$path = \Drupal::service('path.alias_manager')->getPathByAlias('/this-is-the-alias');
if(preg_match('/node\/(\d+)/', $path, $matches)) {
    $node = \Drupal\node\Entity\Node::load($matches[1]);
}

我知道可以通过实体查询找到多个节点:

$nids = \Drupal::entityQuery('node')
            ->condition('type','page')
            ->condition('status',1)
            ->sort('created', 'DESC')
            ->range(0, 20)
            ->execute();

但我想知道如何实现一个额外的条件,通过URL别名的一部分来过滤节点,例如“/news/*”。 我需要所有具有此URL片段的节点。


服务名称为 path_alias.manager。因此,您的问题代码的第一行应该是:$path = \Drupal::service('path_alias.manager')->getPathByAlias('/this-is-the-alias');。谢谢,我已经在您的问题中找到了答案。 - Reza Bayat
2个回答

1

您可以尝试这个方法 - 参考 https://www.jonkamke.com/blog/2019/5/load-a-node-via-url-alias

  <?php
    /** @var Drupal\Core\Url $url */
    $url = $variables['url'];
    if ($url instanceof Drupal\Core\Url) {
      $nid = $url->getRouteParameters()['node'];
      /** @var \Drupal\node\Entity\Node $node */
      $node = Node::load($nid);
      if ($node instanceof Node) {
        $type = $node->getType();
      }
    }

0
$input = '/this-is-the-alias';
$node_query_result = [];
$path_query = \Drupal::database()->select('path_alias', 'a');
$path_query->addField('a', 'path');
$path_query->condition('a.alias', '%' . $input . '%', 'LIKE');
$path_query_result = str_replace('/node/', '', $path_query->execute()->fetchCol());
if ($path_query_result) {
  $node_query = \Drupal::database()->select('node_field_data', 'n');
  $node_query->addField('n', 'nid');
  $node_query->addField('n', 'type');
  $node_query->addField('n', 'title');
  $node_query->condition('n.status', NodeInterface::PUBLISHED);
  $node_query->condition('nid', $path_query_result, 'IN');
  $node_query_result = $node_query->execute()->fetchAll(\PDO::FETCH_ASSOC);
}
return $node_query_result;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接