两个单独的数据库查询将单独的表与Drupal 7模块相关联?

时间:2014-01-12 02:29:11

标签: sql database drupal standards

我正在为我正在处理的网站开发一个自定义模块,并创建了以下代码。这是我的第一个模块,因此任何关于我可以做得更好的想法都会受到赞赏。

实际上,这个模块对我来说非常适合。但是,我想优化它,并确保我修复伪劣的代码。

谢谢!

有问题的功能如下:

// Declared variables for future incrementation
$total=0;
$countOne=0;
$countTwo=0;
$countThree=0;
$countOld=0;

// Call the native global user object from Drupal
global $user;
$userID = $user->uid;       

// Check for nodes of given type owned by current user
$sql = db_query("SELECT nid FROM {node} WHERE type = 'content_type' AND uid = " . $userID);     

// Iteratively checks each node id against a custom Drupal field on a separate table
foreach ($sql as $record) {         

// SQL query for all custom fields attached to the node id given above
$query = db_query("SELECT * FROM {field_birth} WHERE entity_id = " . $record->nid);         
$result = $query->fetchObject();                

// The unmodified birth format (Y-m-d 00:00:00)
$originalBirth = $result->field_date_of_birth_value;

// The sanitized birth format for comparison (Y-m-d)
$birth = date('Y-m-d', strtotime($originalBirth));

// The current date/time (Y-m-d)
$now = date('Y-m-d');

//Future dates (Y-m-d)
$one_year = date('Y-m-d', strtotime('+1 year', strtotime($birth)));
$two_years = date('Y-m-d', strtotime('+2 years', strtotime($birth)));
$three_years = date('Y-m-d', strtotime('+3 years', strtotime($birth)));         

// A count of all records returned before logical statements
$total++;

// Logic to determine the age of the records
if($now < $one_year) {
    $countOne++;
}               
else if($now >= $one_year && $now < $two_years) {
    $countTwo++;
}
else if($now >= $two_years && $now < $three_years) {
    $countThree++;
}
else {
    $countOld++;
}           

我的问题是,我可以避免两个单独的数据库查询来同时触及两个表吗?我真的不确定如何去做。另外,我是以资源密集型和低效率的方式做事吗?因为我不是交易程序员,所以我不确定代码何时“好”。我确实想尽力制作这个好的代码,因为它是一个网站模块,我希望能持续很长时间。

谢谢stackoverflow社区!

编辑:感谢迈克的工作代码如下。如果有人有类似的问题/问题希望这会有所帮助!

// Join field_birth_table to nodes of given type owned by current user      
$sql = db_select('node', 'n');      
$sql->join('field_birth_table', 'b', 'n.nid = b.entity_id');
$sql

    ->fields('b', array('field_birth_field_value', 'entity_id'))
    ->condition('n.type', 'content_type')
    ->condition('n.status', '1')
    ->condition('n.uid', $user->uid)
    ->addTag('node_access');

    $results = $sql->execute();

1 个答案:

答案 0 :(得分:0)

您可以在nodefield_birth表之间使用左连接:

$query = db_select('node', 'n');

$query->leftJoin('field_birth', 'b', '(b.entity_id = n.nid AND b.entity_type = :node)', array(':node' => 'node'));
$query
    ->fields('b', array())
    ->condition('n.type', 'content_type')
    ->condition('n.uid', $user->uid)

$results = $query->execute();