กำลังมองหาตัวอย่างการแทรกฐานข้อมูล


12

ตามdb_insertหน้าคู่มือฟังก์ชั่นนี้เลิกใช้และเป็นการดีกว่าที่จะใช้การเชื่อมต่อฐานข้อมูล Drupal 8 เพื่อทำการแทรก

เลิก

ตั้งแต่ Drupal 8.0.x จะถูกลบใน Drupal 9.0.0 รับการเชื่อมต่อฐานข้อมูลเข้าสู่บริการของคุณแทนจากคอนเทนเนอร์และ call insert () ตัวอย่างเช่น $ injected_database-> insert ($ table, $ options);

ตอนนี้ฉันจะได้รับการเชื่อมต่อฐานข้อมูลและinsert()วิธีการโทรได้อย่างไร


คุณหมายถึงนอกห้องเรียนด้วยบริการฉีดหรือไม่? ชอบ\Drupal::database()->insert(...);ไหม
ไคลฟ์

ไม่ฉันหมายถึงในห้องเรียนด้วยบริการฉีดclass PetmdController extends ControllerBase
โมฮัมหมัดอาลีอั

คำตอบ:


19

เมื่อต้องการฉีดบริการฐานข้อมูลเพิ่ม / เปลี่ยนวิธีการต่อไปนี้ในคลาสตัวควบคุมของคุณ:

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Database\Connection;
use Symfony\Component\DependencyInjection\ContainerInterface;

class PetmdController extends ControllerBase {

  protected $database;

  public function __construct(Connection $database) {
    $this->database = $database;
  }

  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('database')
    );
  }

  public function foo() {
    $this->database->insert(...)->fields(...)->execute();
  }
}

สิ่งนี้ใช้งานได้ดีสำหรับ ControllerBase แต่ฉันจะฉีดบริการฐานข้อมูลได้อย่างไรถ้าคลาสของฉันขยาย ContentEntityBase ที่ส่งตัวแปรต่าง ๆ ไปยังโครงสร้างแล้ว
เฟลิกซ์อีฟ

3

เพื่อเพิ่มคำตอบของ Berdir ที่นี่คือวิธีที่คุณสามารถฉีดบริการฐานข้อมูลของคุณในคอนโทรลเลอร์ของคุณ

$db = \Drupal::database();
      $query = $db->select('location','loc');
      $query->fields('loc', array('id', 'name', 'bond_goal','deposit_goal','date_created','date_updated'));
      $query->addField('loc','name','location_title');
      $table_sort = $query->extend('Drupal\Core\Database\Query\TableSortExtender')->orderByHeader($header);
      $pager = $table_sort->extend('Drupal\Core\Database\Query\PagerSelectExtender')->limit(10);

คุณสามารถศึกษาcore/lib/Drupal/Core/Database/Queryชั้นเรียนสำหรับข้อมูลเพิ่มเติม


2

ขั้นแรกให้เป็นคำพูดของคุณบอกว่ามันจะเลิกสำหรับDrupal 9 ซึ่งหมายความว่าจะอยู่ได้นานหลายปีและจะไม่ถูกลบออกจาก Drupal 8 เลย

แต่ใช่มันเป็นความคิดที่ดีที่จะหลีกเลี่ยงฟังก์ชั่นที่เลิกใช้แล้ว เช่นเดียวกับฟังก์ชั่นอื่น ๆ ที่เลิกใช้แล้วคุณสามารถดูการใช้งานของมันเพื่อดูว่ามันเป็นวิธีการใหม่แบบไหน แม้ว่าแทนที่จะเรียกไปที่ \ Drupal คุณต้องการฉีดฐานข้อมูลหรือบริการอื่น ๆ ที่คุณต้องการเมื่อเป็นไปได้ (เมื่อคุณอยู่ในบริการตัวควบคุมรูปแบบปลั๊กอิน ... )


1

ตัวเลือกที่ 1:

$db = \Drupal::database();
$query = $db->select('k_product', 'p');
$query->fields('p', ['idpr', 'name', 'type']);
$data = $query->execute()->fetchAllAssoc('idpr', 'name', 'type');

ตัวเลือก 2

$db = \Drupal::database();
$data = $db->query('SELECT idpr, name, code, detail FROM k_product')->fetchAllAssoc('idpr', 'name');
โดยการใช้ไซต์ของเรา หมายความว่าคุณได้อ่านและทำความเข้าใจนโยบายคุกกี้และนโยบายความเป็นส่วนตัวของเราแล้ว
Licensed under cc by-sa 3.0 with attribution required.