2017-08-14 47 views
1

在我的Drupal的代碼,我寫了下面的代碼和它正常工作與幾個記錄作爲結果Drupal的JOIN與db_query作品,但不是在db_select

代碼

$result = db_query("SELECT f1 
      FROM table1 as n 
      JOIN table2 as om ON n.f1 = om.f1 
      JOIN table3 as fs ON n.f1 = fs.f1 
      JOIN table4 as sm ON fs.f2 = sm.f1 
      WHERE om.f2 = :f2 
      AND om.f3 = 'type' 
      AND sm.f2 = 'yes' 
      AND sm.f4 = :f4 
      AND n.type = 'test'", array(':f2' => $f2,':f4' => $f4)); 
$record = $result->fetchAll(); 

然後我將上面的代碼轉換爲Drupal代碼生成器格式,如下面的,但它返回空記錄結果

代碼

$record = db_select('table1', 'n'); 
$record -> fields('n', array('f1')) 
    -> condition('om.f2', $f2, '=') 
    -> condition('om.f3', 'type', '=') 
    -> condition('sm.f2', 'yes', '=') 
    -> condition('sm.f4', $f4, '=') 
    -> condition('n.type', 'test', '='); 
$record -> join('table2', 'om', 'n.f1 = om.f1'); 
$record -> join('table3', 'fs', 'n.f1 = fs.f1'); 
$record -> join('table4', 'sm', 'fs.f2 = sm.f1'); 
$record -> execute() 
    -> fetchAll(); 

我無法找到任何代碼的問題。難道我做錯了什麼?

回答

2

請試試這個,

<?php 
 
$record = db_select('table1', 'n'); 
 
$record -> join('table2', 'om', 'n.f1 = om.f1'); 
 
$record -> join('table3', 'fs', 'n.f1 = fs.f1'); 
 
$record -> join('table4', 'sm', 'fs.f2 = sm.f1'); 
 
$result = $record 
 
    ->fields('n', array('f1')) 
 
    -> condition('om.f2', $f2, '=') 
 
    -> condition('om.f3', 'type', '=') 
 
    -> condition('sm.f2', 'yes', '=') 
 
    -> condition('sm.f4', $f4, '=') 
 
    -> condition('n.type', 'test', '='); 
 
    ->execute(); 
 
    ->fetchAll(); 
 

 
foreach ($result as $row) { 
 
    // Do something with $row. 
 
}

+0

大。完美的作品。謝謝 – Arun

+0

@arun:welcome :) –

+0

如果可能,請解釋爲什麼其他方式不起作用? – Arun