To answer my own question I guess(better alternatives are more than welcome).
use Drupal\Core\Entity\EntityTypeManagerInterface;
class SomeRepository {
/**
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entity_type_manager;
/**
* ProductRepository constructor.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
*/
public function __construct(EntityTypeManagerInterface $entity_type_manager) {
$this->entity_type_manager = $entity_type_manager;
}
/**
* @param $node_id
*
* @return array|null
* @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
* @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
*/
public function getNodeComments($node_id) {
try{
$node = $this->entity_type_manager
->getStorage('node')
->load($node_id);
}catch(\Exception $exception) {
// log here
// rethrow error or return, whatever works for you
return NULL;
}
try{
$comment_ids = $this->entity_type_manager
->getStorage('comment')
->getQuery('AND')
->condition('entity_id', $node->id())
->condition('entity_type', 'node')
->sort('cid', 'DESC')
->execute();
}catch(\Exception $exception) {
// log here
// rethrow error or return, whatever works for you
return NULL;
}
if(empty($comment_ids)) {
return [];
}
$comments = $this->entity_type_manager
->getStorage('comment')
->loadMultiple($comment_ids);
$comments_array = [];
foreach($comments as $comment) {
// Loop over and get whichever fields you want from the comments
$comments_array[$comment->id()] = [
'cid' => $comment->id(),
'owner_id' => $comment->getOwnerId(), // node to which this comment belongs
'some_field' => $comment->get('some_field')->value
];
}
return $comments_array;
}
}