我有一个模块,程序化地将许多节点添加到我的Drupal 7网站上。为了避免重复,我想要检查是否在系统中已经存在了刚刚新建的节点标题。永远不会有两个节点拥有相同的名称。我尝试使用
我被卡住了,所以想知道这里是否有人可以帮助我。
总结一下:如何检查某个标题的节点是否已经存在?
谢谢。
node_load()
,但似乎不能根据标题加载节点。我被卡住了,所以想知道这里是否有人可以帮助我。
总结一下:如何检查某个标题的节点是否已经存在?
谢谢。
node_load()
,但似乎不能根据标题加载节点。节点是实体,因此您可以使用EntityFieldQuery类来查询它们。这样,您就不必担心信息在数据库中的存储方式。如果需要根据字段值添加其他筛选条件,代码演变也会更加容易。
$result = (new EntityFieldQuery())
->entityCondition('entity_type', 'node')
->propertyCondition('title', $title)
->execute();
$title_is_unique = empty($result['node']);
(new EntityFieldQuery())->
,但按照原来的写法,这应该会导致致命错误。 - Clive $row = db_query('SELECT nid FROM {node} WHERE title = :mytitle', array(':mytitle' => $myNewTitle))->fetchField();
if(!isset($row['nid'])) {
//safe to continue
} else {
//that title is already there and its in node with node id "nid"
}
如果没有返回结果,则可以认为一切正常。
或者,您可以编辑节点表使标题字段唯一,并处理MySQL抛出的错误。不过我不确定这是否可行。
$query = db_select('node', 'n')
->fields('n', array('nid'))
->condition('n.title', $myNewTitle, '=');
return $query->countQuery()->execute()->fetchField();
node_load_multiple(array(), array('title' => $title));
友情提醒:为了安全起见,您在Drupal SQL查询中应始终使用花括号({})包围表格!这可以防止SQL注入攻击。
因此,正确的写法应该是:(请注意{node})
$row = db_query('SELECT nid FROM {node} WHERE title = :mytitle', array(':mytitle' => $myNewTitle))->fetchField();
if(!isset($row['nid'])) {
//safe to continue
} else {
//that title is already there and its in node with node id "nid"
}
db_add_unique_key("{node}", "title_uniq", array("title"));