Drupal 8 : Entity Query and DB (Database) Query

Entity Query

In Drupal entityQuery allows Web developers to query Drupal entities and its fields in a SQL-like way. A Drupal site's tables and fields are never a 1-to-1 match for the site's entities and fields - entityQuery allows us to query the database as if they were 1-to-1 ways.

Much like you could write some SQL that returns all rows of table1 where field1 is 14, using entityQuery you can ask Drupal to return all entities of type "basic page" where the value of field_some_field is 14. 
Developers can write an entityQuery using the following method to return the QueryInterface:

$query = \Drupal::entityQuery(string $entity_type_id);

Example 1: Simple node entity queries 

This first example returns all nodes of type page where the value of field_some_field (an integer field) is 14.

$query = \Drupal::entityQuery('node')
  ->condition('type', 'page')
  ->condition('field_some_field', 14);
$results = $query->execute();

This example shows that an entityQuery is built up by adding various conditions, sorts, ranges, and other qualifiers. Note that the $query methods are all chainable - each one returns the $query, so we can add multiple conditions per line. 

For conditions, the default operator is "=", so in both of the conditions shown above, the EntityQuery is looking for type=page and field_some_field=14. If we wanted to find all basic page nodes where field_some_field > 14, then the entityQuery would look like this:

$query = \Drupal::entityQuery('node')
  ->condition('type', 'page')
  ->condition('field_some_field', 14, '>');
$results = $query->execute();

 entityQuery() discovery is the fact that it can be used to query field values of referenced entities.

DB Query

A database query is a request for data from a database. Usually the request is to retrieve data; however, data can also be manipulated using queries. The data can come from one or more tables, or even other queries.
OR

A database query is a way of requesting information from the database. A database query can be either a select query or an action query. A select query is a query for retrieving data, while an action query requests additional actions to be performed on the data, like deletion, insertion, and updating.

For example, a manager can perform a query to select the employees who were hired 5 months ago. The results could be the basis for creating performance evaluations.

Example of a Query
As mentioned a moment ago, when we ask Siri for a joke, we are posing a question or query to the application. While the query behind the scenes is very complex and will search against many sources, the concept can be made quite simple.

A query starts with the keyword SELECT, no matter the system. This tells the database to go pick something; the details are after the SELECT statement. If we want all jokes, we use the asterisk (*), which tells the database to retrieve everything:

SELECT * FROM tblJokes;

SELECT * FROM tblJokes WHERE clean_joke = 1;

Drupal 8 Batch Process

Batch process is the process of execution of a program in a series without interference of external source manually. In a Batch process, inputs are taken in batches or slots. However, now this has become more irrelevant with the term batch and essentially means to run a process or a job without an end user’s interaction. In Drupal, batch process will help to execute a similar program.

According to Drupal.org batch operations can be defined as “...function allowing form processing spread out over several page requests, ensuring that the processing does not get interrupted because of a PHP timeout while also allowing the user to receive feedback on the progress of the ongoing operations.”.

In Drupal, without PHP, the timeout can be set using Batch API to perform programming operations smoothly.

In our case we will create a batch process to delete all Node. 

So let’s create a small module for that.

Module Setup:

batch_example.info.yml


name: batch_example

type: module

description: Example module for batch process

core: 8.x

package: Example


Let’s create routing.yml

batch_example.routing.yml

batch_example.delete_node_example:

  path: '/batch-example/delete'

  defaults:

    _form: '\Drupal\batch_example\Form\DeleteNodeForm'

    _title: 'Batch Example'

  requirements:

    _permission: 'access content'

src/Form/DeleteNodeForm.php

Here in the form we just need a submit button to handle the request.

<?php
namespace Drupal\batch_example\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Class DeleteNodeForm.
*
* @package Drupal\batch_example\Form
*/
class DeleteNodeForm extends FormBase {
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'delete_node_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$form['delete_node'] = array(
'#type' => 'submit',
'#value' => $this->t('Delete Node'),
);
return $form;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$nids = \Drupal::entityQuery('node')
->condition('type', 'article')
->sort('created', 'ASC')
->execute();
$batch = array(
'title' => t('Deleting Node...'),
'operations' => array(
array(
'\Drupal\batch_example\DeleteNode::deleteNodeExample',
array($nids)
),
),
'finished' => '\Drupal\batch_example\DeleteNode::deleteNodeExampleFinishedCallback',
);
batch_set($batch);
}
}


Here in the submission handler where we have defined the batch. 

$batch is an array of steps to be performed in batch process. In this batch we have two steps,

deleteNodeExample : In this method we will be handling deletion of node.

deleteNodeExampleFinishedCallback: This is the finish call back it will be called once deletion of all node is done. It will give the status message of the process.

Batch_set : Drupal batch_set method will execute set of operations in made in batches, so as to not interrupt processing.  

Now we need to define these methods, So will create a class say “DeleteNode” inside src directory.

src/DeleteNode.php

<?php
namespace Drupal\batch_example;
use Drupal\node\Entity\Node;
class DeleteNode {
public static function deleteNodeExample($nids, &$context){
$message = 'Deleting Node...';
$results = array();
foreach ($nids as $nid) {
$node = Node::load($nid);
$results[] = $node->delete();
}
$context['message'] = $message;
$context['results'] = $results;
}
function deleteNodeExampleFinishedCallback($success, $results, $operations) {
// The 'success' parameter means no fatal PHP errors were detected. All
// other error management should be handled using 'results'.
if ($success) {
$message = \Drupal::translation()->formatPlural(
count($results),
'One post processed.', '@count posts processed.'
);
}
else {
$message = t('Finished with an error.');
}
drupal_set_message($message);
}
}

This was all about creating batch process in Drupal 8

Write a program in PHP to reverse a number

A number can be written in reverse order. For example 12345 = 54321 <?php   $ num = 23456;   $ revnum = 0;   while ($ num > 1)   {   $...