Database connection can be injected in class object using dependency injection.
We can also use service method
This way of using database is suitable for XXX.module file but in class we can use dependency injection.
Using dependency injection :-
Drupal\Core\Database\Connection class for database connection.
$container->get('database') here database is the service.
For insert query :-
For checking table exists :-
We can also use service method
\Drupal::database()
This way of using database is suitable for XXX.module file but in class we can use dependency injection.
Using dependency injection :-
Drupal\Core\Database\Connection class for database connection.
use Drupal\Core\Database\Connection; use Symfony\Component\DependencyInjection\ContainerInterface; class CustomClass { /** * The database connection to be used. * * @var \Drupal\Core\Database\Connection */ protected $database; /** * @param \Drupal\Core\Database\Connection $database * The database connection to be used. */ public function __construct(Connection $database) { $this->database = $database; } /** * {@inheritdoc} */ public static function create(ContainerInterface $container) { $container->get('database') } }
$container->get('database') here database is the service.
How to use it
For insert query :-
$query = $this->database->insert('custom_table') ->fields(['id', 'message']) ->values([1, 'some text']); $result = $query->execute();
For checking table exists :-
$database_schema = $this->database->schema(); if (!($database_schema->tableExists('custom_table'))) { return FALSE; }
Comments
Post a Comment