4

获取存储在自定义 Drupal 节点中特定字段中的值的“正确”方法是什么?我创建了一个带有自定义节点和自定义URL字段的自定义模块。以下作品:

$result = db_query("SELECT nid FROM {node} WHERE title = :title AND type = :type", array(
  ':title' => $title,
  ':type' => 'custom',
))->fetchField();
$node = node_load($result);
$url = $node->url['und']['0']['value'];

...但是有没有更好的方法,也许使用新的 Field API 函数?

4

3 回答 3

6

node_load()然后将字段作为属性访问是正确的方法,尽管我会稍有不同以避免对语言环境进行硬编码:

$lang = LANGUAGE_NONE;
$node = node_load($nid);
$url = $node->url[$lang][0]['value'];

你用来获取nid的方法是一种特别笨拙的方法。我将专注于重构并使用EntityFieldQueryand entity_load()代替:

$query = new EntityFieldQuery;
$result = $query
  ->entityCondition('entity_type', 'node')
  ->propertyCondition('type', $node_type)
  ->propertyCondition('title', $title)
  ->execute();

// $result['node'] contains a list of nids where the title matches
if (!empty($result['node']) {
  // You could use node_load_multiple() instead of entity_load() for nodes
  $nodes = entity_load('node', $result['node']);
}

您尤其希望这样做,因为 title 不是唯一属性,并且如果该字段出现在节点以外的实体上。在这种情况下,您将删除entityCondition().

于 2011-01-17T02:34:37.720 回答
1

不确定为什么要讨论 EntityFieldQuery,但可以。:) 你实际上会想要使用field_get_items()函数。

if ($nodes = node_load_multiple(array(), array('type' => 'custom', 'title' => $title)) {
  $node = reset($nodes);
  if ($items = field_get_items('node', $node, 'url')) {
    $url = $items[0]['value'];
    // Do whatever
  }
}
于 2011-01-17T05:16:44.100 回答
-1

propertyCondition('field_order_no', 'value', '搜索键', '=')

field_order_no 是自定义字段的 slug & Search Key 是要匹配的值

于 2015-03-11T16:51:01.413 回答