简体   繁体   English

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

[英]Check if the entry in DB exists - Drupal 7

I have made a module that when cron run it gets the wid and variables and timestamp from the watchdog table and pass it in a new table blablabla. 我制作了一个模块,当cron运行时,它会从看门狗表中获取wid和变量以及时间戳,并将其传递到新表中。 I want if a value with same variables exists in the blablabla table do not pass this value. 我想如果blablabla表中存在具有相同变量的值,则不要传递该值。 Here follow my code: 这里按照我的代码:

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

You need to query the table to see if the data exists before writing to it, if a row exists matching the criteria then do nothing. 您需要在写入表之前查询该表以查看数据是否存在,如果存在符合条件的行,则什么也不做。 For example; 例如;

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);
    }       
  }
}

Pretty difficult to give an example given that you're missing the blablabla_table() function in your question, I assume it writes to the blablabla_table. 鉴于您在问题中缺少blablabla_table()函数,因此很难给出一个示例,我认为它会写入blablabla_table。 In the future ask questions without placeholder names. 以后问没有占位符名称的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM