How can I convert this sql query into a Drupal 8 query?
I need all nodes of type 'page' that has not been referenced by nodes of type 'article'. Article content type contains an entity reference field, from where nodes of type 'page' can be referenced.
SELECT *
FROM node_field_data
WHERE type = 'page' AND
node_field_data.nid NOT IN (
SELECT 1
FROM node_field_data
LEFT JOIN node__field_ref
ON node_field_data.nid = node__field_ref.entity_id
WHERE type = 'article'
);
I tried with this approach, but it doesn't work:
$sub_result = $this->database->query("
SELECT 1 FROM {node_field_data} n
LEFT JOIN {node__field_ref} r
ON n.nid = r.entity_id
WHERE n.type = :type",
['type' => 'article']
);
$result = $this->database->query("
SELECT * FROM {node_field_data} n
WHERE n.type = :type AND n.nid NOT IN :query", [
'type' => 'page',
'query' => $sub_result
]
);
I get this error:
The website encountered an unexpected error. Please try again later.
Recoverable fatal error: Object of class Drupal\Core\Database\Statement could not be converted to string in Drupal\Core\Database\Statement->execute() (line 59 of core/lib/Drupal/Core/Database/Statement.php).
Drupal\Core\Database\Statement->execute(Array, Array) (Line: 625)
Drupal\Core\Database\Connection->query('
SELECT * FROM {node_field_data} n
WHERE n.type = :type AND n.nid NOT IN :sub_result', Array, Array) (Line: 87)
Drupal\Core\Database\Driver\mysql\Connection->query('
SELECT * FROM {node_field_data} n
WHERE n.type = :type AND n.nid NOT IN :sub_result', Array) (Line: 141)
...
...
...