检查数据库中的条目是否存在 - Drupal 7


Check if the entry in DB exists - Drupal 7

我做了一个模块,当cron运行时,它从看门狗表中获取wid,变量和时间戳,并将其传递到一个新的表中blablabla。我希望如果 blablabla 表中存在具有相同变量的值,请不要传递此值。以下是我的代码:

function blablabla_cron() {
  // Begin building the query.
  $query = db_select('watchdog', 'th')
    ->extend('PagerDefault')
    ->orderBy('wid')
    ->fields('th', array('wid', 'timestamp'))
    ->limit(2000);
  // Fetch the result set.
  $result = $query -> execute();
  // Loop through each item and add to $row.
  foreach ($result as $row) {
    blablabla_table($row);
  }
}
function error_log_jira_table($row) {
  $timestamp = $row -> timestamp;
  $wid = $row -> wid;
  $variables = $row -> variables;
  $nid = db_insert('error_log_jira')
    ->fields(array(
      'timestamp' => $timestamp,
      'wid' => $wid,
      'variables' => $variables
    ))
    ->execute();
}

您需要在写入表之前查询表以查看数据是否存在,如果存在与条件匹配的行,则不执行任何操作。例如;

function blablabla_cron() {
  // Begin building the query.
  $query = db_select('watchdog', 'th')
    ->extend('PagerDefault')
    ->orderBy('wid')
    ->fields('th', array('wid', 'timestamp', 'variables'))
    ->limit(2000);
  // Fetch the result set.
  $result = $query -> execute();
  // Loop through each item and add to $row.
  foreach ($result as $row) {
    // Query Blablabla table for row matching timestamp and variables
    $r = db_select('blablabla', 'b')
      ->fields('b')
      ->condition('timestamp', $row->timestamp, '=')
      ->condition('variables', $row->variables, '=')
      ->execute();
    // If row doesn't exist then create it (I assume blablabla_table creates?)
    if($r->rowCount() == 0) {
      blablabla_table($row);
    }       
  }
}

鉴于您在问题中缺少blablabla_table()函数,很难举出一个例子,我认为它会写入blablabla_table。将来提出没有占位符名称的问题。