获取指定节点类型的最新10篇文章?

时间:2012-11-25 08:27:40

标签: php drupal drupal-7

现在,如果节点类型是文章。在术语页面左侧,我想显示最新的10篇文章的标题,哪个节点类型是文章。我不想使用意见,我该怎么办?谢谢。

如果我想在节点页面的左边显示最新的10篇文章标题,哪个节点类型是文章。如何编写查询。非常感谢。

ps:我发现EntityFieldQuery也许可以做到这一点,但我现在不知道如何做到这一点。

我的代码:

$query = new EntityFieldQuery();

$query
 ->entityCondition('entity_type', 'node')
 ->entityCondition('bundle', 'article')
 ->propertyCondition('status', 1)
 ->propertyOrderBy('created', 'DESC')
  ->range(0, 10);

$result = $query->execute();

3 个答案:

答案 0 :(得分:6)

代码可以是这样的(使用db_select()

$query = db_select("node", "n") // select from the node table
    ->fields("n", array("nid", "title")) // fields nid, title
    ->condition("type", "page", "=") // where the node type = page
    ->orderBy("created", "DESC") // order by the newest
    ->range(0, 10) // select only 10 records
    ->execute(); // execute the query

while($record = $query->fetchAssoc()) {
    print(l($record['title'], "node/" . $record['nid'])); // print the node title linked to node.
}

使用EntityFieldQuery()的另一个例子:

$query = new EntityFieldQuery();
$entities = $query->entityCondition('entity_type', 'node')          
      ->entityCondition('bundle', 'club')
      ->propertyOrderBy("created", "DESC")
      ->range(0, 10)
      ->execute();

foreach($entities['node'] as $obj)
{
    $node = node_load($obj->nid);
    print(l($node->title, "node/" . $node->nid));
}

表现明智:使用第一种方法。

希望这有帮助......穆罕默德。

答案 1 :(得分:2)

我会提到另一个解决方案,因为它是Drupal的好知识。 Views模块可以用很少的工作创建这样的块。学习起来有点棘手,但它非常适合制作这类列表。

答案 2 :(得分:0)

就D7性能而言,最好使用旧的db_query命令:

$result = db_query("SELECT nid FROM {node} WHERE type = :type AND status = 1 ORDER BY created DESC LIMIT 10", array(':type' => $type));
foreach ($result as $record) {
  // Do something with each $record
  $node = node_load($record->nid);
}

要对db_querydb_select进行速度比较,请查看此处:https://www.drupal.org/node/1067802#comment-8996571

  

对于简单查询,db_query()比db_select()

快22%      

对于简单查询,db_query()比EFQ

快124%      

对于具有两个连接的查询,db_query()比db_select()快29%

这是因为db_select和EntityFieldQuery()允许模块挂钩并修改查询。这对你来说可能是件好事!

我只是提供选择。