We have to write a module, something like this
/modules/childs_count/childs_count.views.inc
function childs_count_views_data()
{
$data['taxonomy_term_field_data']['childs_count'] = array(
'title' => t('Childs count'),
'help' => t('Get the number of childs in taxo.'),
'field' => array(
'id' => 'childs_count'
),
'filter' => [
'id' => 'childs_count_filter',
],
);
return $data;
}
/modules/childs_count/childs_count.module
//to do add limit and type..
function childs_count_query($depth = 5)
{
if ($depth < 1) {
$depth = 1;
}
$sql = "(
SELECT COUNT(nid) FROM node_field_data WHERE node_field_data.nid IN (
SELECT tn.nid AS nid FROM taxonomy_index tn
LEFT JOIN taxonomy_term__parent th ON th.entity_id = tn.tid
LEFT JOIN taxonomy_term__parent th1 ON th.parent_target_id = th1.entity_id";
foreach (range(1, $depth - 1) as $level) {
$sql .= "\n\tLEFT JOIN taxonomy_term__parent th" . ($level + 1) . " ON th" . $level . ".parent_target_id = th" . ($level + 1) . ".entity_id\n";
}
$sql .= "WHERE (tn.tid = taxonomy_term_field_data.tid)";
foreach (range(1, $depth) as $level) {
$sql .= "\nOR (th$level.entity_id = taxonomy_term_field_data.tid)";
}
$sql .= ")\n)\n";
return $sql;
}
/modules/childs_count/src/Plugin/views/field/fieldChildsCount.php
namespace Drupal\childs_count\Plugin\views\field;
use Drupal\views\Plugin\views\field\NumericField;
/**
* Field handler for search snippet.
*
* @ingroup views_field_handlers
*
* @ViewsField("childs_count")
*/
class ChildsCount extends NumericField
{
public function query()
{
$this->field_alias="comptage";
$this->query->addField(NULL, childs_count_query(), $this->field_alias);
}
}
/modules/childs_count/src/Plugin/views/filter/ChildsCountFilter.php
namespace Drupal\childs_count\Plugin\views\filter;
use Drupal\Core\Form\FormStateInterface;
use Drupal\views\Plugin\views\filter\NumericFilter;
/**
* Defines a filter for filtering on numeric values.
*
* @ingroup views_filter_handlers
*
* @ViewsFilter("childs_count_filter")
*/
class ChildsCountFilter extends NumericFilter
{
public function query()
{
$this->ensureMyTable();
$where = $this->operator . ' ' . $this->value['value'];
$this->query->addWhereExpression($this->options['group'], childs_count_query() . " $where");
}
/**
* {@inheritdoc}
*/
public function operators()
{
$operators = parent::operators();
unset($operators['regular_expression']);
unset($operators['between']);
unset($operators['not between']);
return $operators;
}
protected function valueForm(&$form, FormStateInterface $form_state)
{
parent::valueForm($form, $form_state);
unset($form['value']['min']);
unset($form['value']['max']);
}
}
I will do it. it's not good for server performance, but it suits me.
Thanks for your help.