2012-06-13 147 views
0

我想在drupal中运行数据库查询,其中内容类型有一个节点关联字段,并且我试图获取当前节点的NID匹配的所有类型的注释在所述音符关联字段中指定的节点。Drupal 7中的数据库查询

视觉例子

Nodetype1 - 节点联想场

NodeType2

我想获得的所有Nodetype1的是节点联想场当前加载Nodetype2的NID匹配。

我现在的分贝查询,像这样:

db_query("SELECT * FROM field_data_field_promo_profile WHERE field_promo_profile_nid=".$N->nid); 

,这没有返回,当我知道一个事实,即这样的节点存在,我也试过丢弃WHERE语句,并返回一个这样的数组:

DatabaseStatementBase Object ([dbh] => DatabaseConnection_mysql Object ([shutdownRegistered:protected] => [target:protected] => default [key:protected] => default [logger:protected] => [transactionLayers:protected] => Array () [driverClasses:protected] => Array ([SelectQuery] => SelectQuery [DatabaseSchema] => DatabaseSchema_mysql [MergeQuery] => MergeQuery [DatabaseTransaction] => DatabaseTransaction [UpdateQuery] => UpdateQuery [InsertQuery] => InsertQuery_mysql) [statementClass:protected] => DatabaseStatementBase [transactionSupport:protected] => 1 [transactionalDDLSupport:protected] => [temporaryNameIndex:protected] => 0 [connectionOptions:protected] => Array ([database] => cityhound_dev [username] => blahblah [password] => blahblah [host] => localhost [port] => [driver] => mysql [prefix] => Array ([default] =>)) [schema:protected] => DatabaseSchema_mysql Object ([connection:protected] => DatabaseConnection_mysql Object *RECURSION* [placeholder:protected] => 0 [defaultSchema:protected] => public [uniqueIdentifier:protected] => 4fd7fba9e563e2.50177866) [prefixes:protected] => Array ([default] =>) [prefixSearch:protected] => Array ([0] => { [1] => }) [prefixReplace:protected] => Array ([0] => [1] =>)) [queryString] => SELECT * FROM field_data_field_promo_profile) 

任何人有一些想法?

回答

0

db_query()返回一个迭代的对象,所以你只需要遍历它:

$result = db_query("SELECT * FROM field_data_field_promo_profile WHERE field_promo_profile_nid=".$N->nid); 

foreach ($result as $row) { 
    $entity_id = $row->entity_id; 
    // etc... 
} 
+0

好吧,我会试试这个,我怎么测试,如果结果是空的,因为即使它没有返回它不是一个空数组,当它是空的时候,它会在所有地方抛出错误。 – flaiks

+0

看到我试过这个,它返回数据库错误,这可能是因为即时查询字段和节点的内容类型? – flaiks

0

您应该使用参数在查询,以防止SQL注入。

例如上面的查询应该是这样的:

 

$result = db_query("SELECT * FROM {field_data_field_promo_profile} p 
    WHERE p.field_promo_profile_nid = :nid ", array(':nid' => $N->nid); 

foreach ($result as $row) { 
    $entity_id = $row->entity_id; 
    // etc... 
}