Drupal JOIN适用于db_query,但不适用于db_select

时间:2017-08-14 12:59:49

标签: php drupal-7

在我的drupal代码中,我编写了以下代码,它可以很好地处理结果很少的记录

代码

$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();

我发现代码没有任何问题。我做错了吗?

1 个答案:

答案 0 :(得分: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.
}