【问题标题】:Drupal 8 - Get All Nodes With a Part of Url AliasDrupal 8 - 获取具有部分 URL 别名的所有节点
【发布时间】:2020-09-30 14:21:11
【问题描述】:

我试图找到一种方法来通过节点中的 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');。谢谢,我在你的问题中找到了答案

标签: drupal drupal-8


【解决方案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();
      }
    }

【讨论】:

    【解决方案2】:
    $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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多