【发布时间】:2014-01-12 02:29:11
【问题描述】:
我正在为我正在开发的网站开发一个自定义模块,并创建了以下代码。这是我的第一个模块,所以任何关于我可以做得更好的想法都将不胜感激。
事实上,这个模块非常适合我。但是,我想优化它并确保我修复了伪劣代码。
谢谢!
有问题的函数如下:
// 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 社区!
编辑:感谢 Mike,我得到的代码如下。如果有人有类似的问题/问题,希望这会有所帮助!
// 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();
【问题讨论】:
标签: sql database drupal standards