2012-06-13 72 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... 
}