Last active
November 6, 2021 12:37
-
-
Save DanLaufer/f2e0735541afc65a2ea5d4ca29c8b966 to your computer and use it in GitHub Desktop.
Drupal 8 - EntityQuery stuff
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// chaining with .entity. | |
$query = \Drupal::entityQuery('node'); | |
$articles_by_name = $query->condition('type', 'article') | |
->condition('uid.entity.name', 'admin') | |
->execute(); | |
//Equal/>=/<=/etc (3rd parameter) | |
// Find particular nodes published in the last year. | |
$query = \Drupal::entityQuery('node'); | |
$now = time(); | |
$last_year = $now - 60*60*24*365; | |
$last_years_articles = $query->condition('type', 'article') | |
->condition('created', $last_year, '>=') | |
->execute(); | |
//And/Or - [and,or]ConditionGroup() | |
$query = \Drupal::entityQuery('node'); | |
$group = $query->orConditionGroup() | |
->condition('uid', 22) | |
->condition('uid', 14) | |
->condition('uid.entity.name', 'admin') | |
$entity_ids = $query->condition('type', 'article') | |
->condition($group) | |
->execute(); | |
// Exists | |
$query = \Drupal::entityQuery('node'); | |
$untagged_articles = $query->condition('type', 'article') | |
->notExists('field_tags') | |
->execute(); | |
// Count | |
$query = \Drupal::entityQuery('user'); | |
$time = time(); | |
$yesterday = $time - 60*60*24; | |
$new_user_count = $query->condition('created', $yesterday, '>=') | |
->count() | |
->execute(); | |
// Sort | |
$query = \Drupal::entityQuery('user'); | |
$time = time(); | |
$yesterday = $time - 60*60*24; | |
$new_users = $query->condition('created', $yesterday, '>=') | |
->sort('created', 'DESC') | |
->execute(); | |
// Range / Pager | |
$query = \Drupal::entityQuery('node'); | |
$newest_articles = $query->condition('type', 'article') | |
->condition('status', 1) | |
// Only return the newest 10 articles | |
->sort('created', 'DESC') | |
->pager(10) | |
->execute(); | |
$not_quite_as_new_articles = $query->condition('type', 'article') | |
->condition('status', 1) | |
// Only return the next newest 10 articles | |
->sort('created', 'DESC') | |
->range(10, 10) | |
->execute(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment