开发者

drupal insert or update DB record with only one function

开发者 https://www.devze.com 2023-04-08 17:41 出处:网络
similar quest is here: Help with db query in drupal - if exists update else insert But drupal_write_record() third argument is to 开发者_运维知识库determine update or insert. Maybe drupal has another

similar quest is here: Help with db query in drupal - if exists update else insert

But drupal_write_record() third argument is to 开发者_运维知识库determine update or insert. Maybe drupal has another function, who self determine insert or update by primary key? Or I should it to program my self?


Have a look at the db_merge() function, I think it has the features you're looking for.


If you really don't know if there's a record there already, you probably need to check a bit earlier in your program flow. Normally I'd start the function or whatever with a call to the DB and if I don't get an existing record object, I make a new one from stdClass.

This has two benefits: first, it means that you know about existing data, so you can use it if needs be and not overwrite it blindly. Second: when you get to the point where you write to the DB, you know whether it's INSERT or UPDATE based on whether the object has an id property.


I implemented function myself:

function drupal_write_record2($table, $data, $primaryKeys) {
   $data = (array)$data;

   $query = db_select($table)
      ->fields($table);

   if (is_array($primaryKeys))
      foreach ($primaryKeys as $key)
         $query->condition($key, $data[$key]);
   else
      $query->condition($primaryKeys, $data[$primaryKeys]);

   $update = (bool)$query->execute()->fetchAssoc();

   if ($update)
      return drupal_write_record($table, $data, $primaryKeys);
   else
      return drupal_write_record($table, $data);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消