My Select function of my QueryManager:
/**
* Führt eine SELECT - Query durch
*
* #param $select = array( array(column, [...]), table, shortcut )
* $orderby = array(column, sorting-type)
* $where = array( array( column, value, type[or, and] ), [...] )
* $innerjoin = array( table, shortcut, condition )
* $pagination = array( page, limit )
*
* #return array $data
*/
public function select($select,$orderby, $where, $innerjoin, $pagination)
{
$qb = $this->conn->createQueryBuilder()
->select($select[0])
->from($select[1], $select[2])
;
if ($orderby) {
$qb->orderBy($orderby);
}
if ($where) {
foreach($where as $cond) {
$x = 0;
if ( key($cond) == 0 ) {
$qb
->where($cond[0] . ' = ?')
->setParameter($x,$cond[1]);
}
elseif ( $cond[2] == 'and' ) {
$qb
->andWhere($cond[0] . ' = ?')
->setParameter($x,$cond[1]);
}
elseif ( $cond[2] == 'and' ) {
$qb
->orWhere($cond[0] . ' = :' . $x)
->setParameter($x,$cond[1]);
}
$x++;
}
}
if ($innerjoin) {
$qb->join($select[2],$innerjoin);
}
$this->sql = $qb->getSQL();
$this->totalRowCount = count( $qb->execute() ) ;
if ($pagination) {
$max = $pagination[0] * $pagination[1];
$first = $max - $limit;
$qb
->setFirstResult($first)
->setMaxResults($max)
;
}
$stmt = $qb->execute();
return $stmt->fetchAll();
}
I don't know why, but in action, this function produces a select query without inserted values for the parameters:
/**
* Lädt einen User nach dessen Username
*
* #param $username
* #return User $user | null
*/
public function getUser($username)
{
if($data = $this->select(array('*','users','u'), null, array( array('username',$username) ), null,null)) {
return $user = $this->hydrate($data);
}
return null;
}
I didn't get a result, and the query is not setup correctly:
array(0) { }
SELECT * FROM users u WHERE username = ?
In my opinion the Builder doesn't supstitute my parameters with the provided values ...
I got the latest version of Doctrine DBAL (2.4) and this version should support this features!
Thanks for Help and Suggestions :)
I also had this Problem. I have readed here doctrine 2 querybuilder with set parameters not working that:
You cant bind parameters to QueryBuilder, only to Query
But im creating SQL conditions as collected AND & OR experssions in deep nested objects, and the toppest object creates the query object. So i cant create the query object before, i always return expression objects.
So i solved the problem with direct including the variable into the prepared variable's position.
$qb->where($cond[0] . '=' . $cond[1]);
And because i expect strings there i added hard coded quotes. This is not the desired way, but at the moment i dont know how to solve that in an other way with binding parameters to the QueryBuilder object.
$expr = $d_qb->expr()->between($t_c, "'" . $date_from . "'", "'" . $date_from . "'");
Other suggestions?
Following codes results:
$expr = $d_qb->expr()->between($t_c, ':from', ':to');
$d_qb->setParameter('from', 1);
$d_qb->setParameter('to', 1);
or
$expr = $d_qb->expr()->between($t_c, ':from', ':to');
$d_qb->setParameter(':from', 1);
$d_qb->setParameter(':to', 1);
Results:
e0_.created BETWEEN ? AND ?
Related
I created a TYPO3 extension which allows to select several images. I activated metadata via the filemetadata extension. When I browse the image files in a fluid template loop, I try to display the metadata. This works {file.properties.uid}
{file.properties.categories}, but for the categories I get a number. Now I would like to have the category selected.
I used this:
https://coding.musikinsnetz.de/typo3/fluid-viewhelpers/access-system-categories-in-content-elements-templates
<f: if condition = "{files}">
<f: for each = "{files}" as = "file">
<f: for each = "{bg2yg: CategoriesOutput (recUid: data.uid)}" as = "category">
<b style = 'color: blue'> <span class = "{category.title}"> CATEGORY: {category.title} </span> </b> <br />
</ f: for>
</ f: for>
</ f: if>
This displays the main category because 'data.uid': {bg2yg: CategoriesOutput (recUid: data.uid)}
However, I want the categories of images, I tested this:
<f: for each = "{bg2yg: CategoriesOutput (recUid: file.properties.uid)}" as = "category">
Without success ! Do you have an idea ?
Best regards,
Bruno
thank you for your respective help. Here I coded this:
<?php
/**
* This file is part of the "hexagonalgallery" Extension for TYPO3 CMS.
*
* For the full copyright and license information, please read the
* LICENSE file that was distributed with this source code.
*/
namespace BG2YG\Hexagonalgallery\ViewHelpers;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper;
/**
* will return certain system categories (sys_category) data of an element
* either as an array or as a string with certain parameters
*
* EXAMPLES:
*
* EMBEDDING IN TEMPLATE: {namespace my = YourVendor\YourExtension\ViewHelpers}
*
* call an array with all category data to be used in a loop, e.g. for an HTML tag for each files:
* <f:if condition="{file}">
* <f:for each="{my:FileCategoriesOutput(recUid: data.uid)}" as="category">
* <span class="{category.title}">{category.title}</span>
* </f:for>
* </f:if>
*
* call a “data-categories” attribute with the slug field of the categories, comma-separated (default):
* {my:FileCategoriesOutput(recUid: file.properties.uid, tableName: 'sys_file_metadata', fieldString: 'title', htmlAttr: 'data-categories')}
* output: ' data-categories="catx,caty"'
*
* call all categories as CSS classes (space as string separator, prefix 'cat-' for each files)
* {my:FileCategoriesOutput(recUid: file.properties.uid, tableName: 'sys_file_metadata', fieldString: 'title', stringSeparator: ' ', catPrefix: 'cat-')}
* output: 'cat-catx cat-caty'
*/
class FileCategoriesOutputViewHelper extends AbstractViewHelper
{
protected $escapeOutput = false;
public function initializeArguments()
{
$this->registerArgument('recUid', 'integer', 'record UID, e.g. of a content element', true);
$this->registerArgument('tableName', 'string', 'optional: table of records you want the categories returned for (default: tt_content)', false, 'tt_content');
$this->registerArgument('fieldString', 'string', 'optional: name of sys_categories table field – if given, the return value will be a string', false, null);
$this->registerArgument('stringSeparator', 'string', 'optional: separator for string', false, ',');
$this->registerArgument('htmlAttr', 'string', 'optional: wrap in attribute for HTML tag (in case of fieldString given)', false, null);
$this->registerArgument('catPrefix', 'string', 'optional: prefix for each category (e.g. for CSS classes)', false, null);
}
/**
* #return mixed
*/
public function render()
{
$recUid = $this->arguments['recUid'];
$tableName = $this->arguments['tableName'];
$fieldString = $this->arguments['fieldString'];
$stringSeparator = $this->arguments['stringSeparator'];
$htmlAttr = $this->arguments['htmlAttr'];
$catPrefix = $this->arguments['catPrefix'];
define(DEBUG,false);
/*
SELECT uid_local FROM sys_file_reference WHERE uid = 152
*/
if (DEBUG)
echo "<b style='color:blue;'>\$recUid=".$recUid."</b><br />";
/**
* default query for sys_file_reference table
* SQL : SELECT uid_local FROM sys_file_reference WHERE uid = $recUid
*/
$queryBuilder0 = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_file_reference');
$queryBuilder0->select('uid_local');
$queryBuilder0->from('sys_file_reference');
$queryBuilder0->where(
$queryBuilder0->expr()->eq('sys_file_reference.uid', $queryBuilder0->createNamedParameter($recUid, \PDO::PARAM_INT)));
$result_uid = $queryBuilder0->execute();
$uid=$result_uid->fetch();
$uid=$uid['uid_local'];
if (DEBUG)
echo "<b style='color:blue;'>\$uid=".print_r($uid)."</b><br />";
/**
* default query for sys_category table
*/
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_category');
/**
* select the fields that will be returned, use asterisk for all
*/
$queryBuilder->select('sys_category.uid', 'sys_category.title', 'sys_category_record_mm.uid_foreign', 'sys_category_record_mm.tablenames');
$queryBuilder->from('sys_category');
$queryBuilder->join(
'sys_category',
'sys_category_record_mm',
'sys_category_record_mm',
$queryBuilder->expr()->eq('sys_category_record_mm.uid_local', $queryBuilder->quoteIdentifier('sys_category.uid'))
);
$queryBuilder->where(
$queryBuilder->expr()->eq('sys_category_record_mm.uid_foreign', $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)),
$queryBuilder->expr()->like('sys_category_record_mm.tablenames', $queryBuilder->createNamedParameter($tableName))
);
$result = $queryBuilder->execute();
$res = [];
$returnString = '';
$i = 1;
while ($row = $result->fetch()) {
$res[] = $row;
if ($fieldString !== null) {
if (isset($row[$fieldString])) {
$returnString .= ($i === 1) ? '' : $stringSeparator;
$returnString .= ($catPrefix !== null) ? $catPrefix : '';
$returnString .= $row[$fieldString];
}
}
$i++;
}
if (DEBUG) {
echo "\$returnString=" . $returnString . "<br />";
echo "\$res=<b style='color:red;'>" . print_r($res) . "</b><br />";
}
if ($returnString !== '') {
return ($htmlAttr !== null)
? ' ' . $htmlAttr . '="' . $returnString . '"'
: $returnString;
} elseif ($fieldString !== null) {
return '';
} else {
return $res;
}
}
}
And it works. Thank you for indicating to me if this code seems to you written in the rules of art.
Best regards,
Bruno
It looks like categories are not handled in the model, so the fastest thing you can do is to create your own ViewHelper for fetching them as suggested in answer to a similar question, my fast test for TYPO3 9.5
IMPORTANT! for ver.: 10+ check annotation changes at the bottom of this post.
<?php
namespace VENDOR\Toolbox\ViewHelpers;
use TYPO3\CMS\Core\Resource\FileReference;
use TYPO3\CMS\Extbase\Persistence\Generic\QueryResult;
use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper;
/**
*
* #package TYPO3
* #subpackage toolbox
* #license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 2 or later
* #author Marcus Biesioroff biesior#gmail.com>
*
* Sample ViewHelper for listing file's categories
*
* Usage:
* {namespace toolbox=VENDOR\Toolbox\ViewHelpers}
* or in ext_tables.php:
* $GLOBALS['TYPO3_CONF_VARS']['SYS']['fluid']['namespaces']['toolbox'] = ['VENDOR\Toolbox\ViewHelpers'];
*
* <toolbox:fileCategories file="{file}" />
* or
* {toolbox:fileCategories(file: file)}
*/
class FileCategoriesViewHelper extends AbstractViewHelper
{
/**
* #var \TYPO3\CMS\Extbase\Domain\Repository\CategoryRepository
* #inject
*/
protected $categoryRepository;
public function initializeArguments()
{
parent::initializeArguments();
$this->registerArgument('file', 'mixed', 'File');
}
public function render()
{
/** #var FileReference $fileRef */
$fileRef = $this->arguments['file'];
$file = $fileRef->getOriginalFile();
$uid = $file->getUid();
/** #var QueryResult $res */
$res = $this->getCategories($uid);
return $res->toArray();
}
private function getCategories($uid)
{
$query = $this->categoryRepository->createQuery();
$sql = "SELECT sys_category.* FROM sys_category
INNER JOIN sys_category_record_mm ON sys_category_record_mm.uid_local = sys_category.uid AND sys_category_record_mm.fieldname = 'categories' AND sys_category_record_mm.tablenames = 'sys_file_metadata'
INNER JOIN sys_file_metadata ON sys_category_record_mm.uid_foreign = sys_file_metadata.uid
WHERE sys_file_metadata.file = '" . (int)$uid . "'
AND sys_category.deleted = 0
ORDER BY sys_category_record_mm.sorting_foreign ASC";
return $query->statement($sql)->execute();
}
}
So you can use it within your Fluid template like:
<h3>File categories:</h3>
<ul>
<f:for each="{toolbox:fileCategories(file: file)}" as="file_cat">
<li>{file_cat.title}</li>
</f:for>
</ul>
Don't forget to use your own vendor and subpackage key.
Of course, after injecting anything don't forget to flush your caches, sometimes maaaany times.
Important info for ver.: 10.* +
According to this article #inject annotation is depreciated in ver. 9.x and removed in ver." 10.x You should use #TYPO3\CMS\Extbase\Annotation\Inject instead.
So proper injection of the categoryRepository in TYPO3 10.x and newer should look like:
/**
* #var \TYPO3\CMS\Extbase\Domain\Repository\CategoryRepository
* #TYPO3\CMS\Extbase\Annotation\Inject
*/
protected $categoryRepository;
You can also search for deprecated annotations within your ext via Upgrade module > Scan Extension Files
Yep, the title suggests: Doctrine is looking for a fieldname that's not there. That's both true and not true at the same time, though I cannot figure out how to fix it.
The full error:
File: D:\path\to\project\vendor\doctrine\dbal\lib\Doctrine\DBAL\Driver\AbstractMySQLDriver.php:71
Message: An exception occurred while executing 'SELECT DISTINCT id_2
FROM (SELECT p0_.name AS name_0, p0_.code AS code_1, p0_.id AS id_2
FROM product_statuses p0_) dctrn_result ORDER BY p0_.language_id ASC, name_0 ASC LIMIT 25
OFFSET 0':
SQLSTATE[42S22]: Column not found: 1054 Unknown column
'p0_.language_id' in 'order clause'
The query the error is caused by (from error above):
SELECT DISTINCT id_2
FROM (
SELECT p0_.name AS name_0, p0_.code AS code_1, p0_.id AS id_2
FROM product_statuses p0_
) dctrn_result
ORDER BY p0_.language_id ASC, name_0 ASC
LIMIT 25 OFFSET 0
Clearly, that query is not going to work. The ORDER BY should be in the sub-query, or else it should replace p0_ in the ORDER BY with dctrn_result and also get the language_id column in the sub-query to be returned.
The query is build using the QueryBuilder in the indexAction of a Controller in Zend Framework. All is very normal and the same function works perfectly fine when using a the addOrderBy() function for a single ORDER BY statement. In this instance I wish to use 2, first by language, then by name. But the above happens.
If someone knows a full solution to this (or maybe it's a bug?), that would be nice. Else a hint in the right direction to help me solve this issue would be greatly appreciated.
Below additional information - Entity and indexAction()
ProductStatus.php - Entity - Note the presence of language_id column
/**
* #ORM\Table(name="product_statuses")
* #ORM\Entity(repositoryClass="Hzw\Product\Repository\ProductStatusRepository")
*/
class ProductStatus extends AbstractEntity
{
/**
* #var string
* #ORM\Column(name="name", type="string", length=255, nullable=false)
*/
protected $name;
/**
* #var string
* #ORM\Column(name="code", type="string", length=255, nullable=false)
*/
protected $code;
/**
* #var Language
* #ORM\ManyToOne(targetEntity="Hzw\Country\Entity\Language")
* #ORM\JoinColumn(name="language_id", referencedColumnName="id")
*/
protected $language;
/**
* #var ArrayCollection|Product[]
* #ORM\OneToMany(targetEntity="Hzw\Product\Entity\Product", mappedBy="status")
*/
protected $products;
[Getters/Setters]
}
IndexAction - Removed parts not directly related to QueryBuilder. Added in comments showing params as they are.
/** #var QueryBuilder $qb */
$qb = $this->getEntityManager()->createQueryBuilder();
$qb->select($asParam) // 'pro'
->from($emEntity, $asParam); // Hzw\Product\Entity\ProductStatus, 'pro'
if (count($queryParams) > 0 && !is_null($query)) {
// [...] creates WHERE statement, unused in this instance
}
if (isset($orderBy)) {
if (is_array($orderBy)) {
// !!! This else is executed !!! <-----
if (is_array($orderDirection)) { // 'ASC'
// [...] other code
} else {
// $orderBy = ['language', 'name'], $orderDirection = 'ASC'
foreach ($orderBy as $orderParam) {
$qb->addOrderBy($asParam . '.' . $orderParam, $orderDirection);
}
}
} else {
// This works fine. A single $orderBy with a single $orderDirection
$qb->addOrderBy($asParam . '.' . $orderBy, $orderDirection);
}
}
================================================
UPDATE: I found the problem
The above issue is not caused by incorrect mapping or a possible bug. It's that the QueryBuilder does not automatically handle associations between entities when creating queries.
My expectation was that when an entity, such as ProductStatus above, contains the id's of the relation (i.e. language_id column), that it would be possible to use those properties in the QueryBuilder without issues.
Please see my own answer below how I fixed my functionality to be able to have a default handling of a single level of nesting (i.e. ProducStatus#language == Language, be able to use language.name as ORDER BY identifier).
Ok, after more searching around and digging into how and where this goes wrong, I found out that Doctrine does not handle relation type properties of entities during the generation of queries; or maybe does not default to using say, the primary key of an entity if nothing is specified.
In the use case of my question above, the language property is of a #ORM\ManyToOne association to the Language entity.
My use case calls for the ability to handle at lease one level of relations for default actions. So after I realized that this is not handled automatically (or with modifications such as language.id or language.name as identifiers) I decided to write a little function for it.
/**
* Adds order by parameters to QueryBuilder.
*
* Supports single level nesting of associations. For example:
*
* Entity Product
* product#name
* product#language.name
*
* Language being associated entity, but must be ordered by name.
*
* #param QueryBuilder $qb
* #param string $tableKey - short alias (e.g. 'tab' with 'table AS tab') used for the starting table
* #param string|array $orderBy - string for single orderBy, array for multiple
* #param string|array $orderDirection - string for single orderDirection (ASC default), array for multiple. Must be same count as $orderBy.
*/
public function createOrderBy(QueryBuilder $qb, $tableKey, $orderBy, $orderDirection = 'ASC')
{
if (!is_array($orderBy)) {
$orderBy = [$orderBy];
}
if (!is_array($orderDirection)) {
$orderDirection = [$orderDirection];
}
// $orderDirection is an array. We check if it's of equal length with $orderBy, else throw an error.
if (count($orderBy) !== count($orderDirection)) {
throw new \InvalidArgumentException(
$this->getTranslator()->translate(
'If you specify both OrderBy and OrderDirection as arrays, they should be of equal length.'
)
);
}
$queryKeys = [$tableKey];
foreach ($orderBy as $key => $orderParam) {
if (strpos($orderParam, '.')) {
if (substr_count($orderParam, '.') === 1) {
list($entity, $property) = explode('.', $orderParam);
$shortName = strtolower(substr($entity, 0, 3)); // Might not be unique...
$shortKey = $shortName . '_' . (count($queryKeys) + 1); // Now it's unique, use $shortKey when continuing
$queryKeys[] = $shortKey;
$shortName = strtolower(substr($entity, 0, 3));
$qb->join($tableKey . '.' . $entity, $shortName, Join::WITH);
$qb->addOrderBy($shortName . '.' . $property, $orderDirection[$key]);
} else {
throw new \InvalidArgumentException(
$this->getTranslator()->translate(
'Only single join statements are supported. Please write a custom function for deeper nesting.'
)
);
}
} else {
$qb->addOrderBy($tableKey . '.' . $orderParam, $orderDirection[$key]);
}
}
}
It by no means supports everything the QueryBuilder offers and is definitely not a final solution. But it gives a starting point and solid "default functionality" for an abstract function.
New to Symfony2 and Doctrine2, i have a function in my entity repository to search entities after form submission. Input is array $get that contain form fields like $get['name'] = 'aname'.
My problem is that when i request with an id, or an id and a name, it's ok by with only a name, all my entities are matched because the query that has been build have no where clause.
Here is my code :
public function search(array $get, $flag = False){
/* Indexed column (used for fast and accurate table cardinality) */
$alias = 'd';
/* DB table to use */
$tableObjectName = 'mysiteMyBundle:DB';
$qb = $this->getEntityManager()
->getRepository($tableObjectName)
->createQueryBuilder($alias)
->select($alias.'.id');
$arr = array();
//Simple array, will grow after problem solved
$numericFields = array(
'id');
$textFields = array(
'name');
while($el = current($get)) {
$field = key($get);
if ( $field == '' or $field == Null or $el == '' or $el == Null ) {
next($get);
}
if ( in_array($field,$numericFields) ){
if ( is_numeric($el) ){
$arr[] = $qb->expr()->eq($alias.".".$field, $el);
}
} else {
if ( in_array($field,$textFields) ) {
$arr[] = $qb->expr()->like($alias.".".$field, $qb->expr()->literal('%'.$el.'%') );
}
}
next($get);
}
if(count($arr) > 0) $qb->andWhere(new Expr\Orx($arr));
else unset($arr);
$query = $qb->getQuery();
if($flag)
return $query;
else
return $query->getResult();
}
The query generated with only a name (ex "myname") input is :
SELECT d0_.id AS id0 FROM DB d0_
It should be:
SELECT d0_.id AS id0 FROM DB d0_ WHERE d0_.name LIKE '%myname%'
What's wrong with my code ?
Thanks !
I don't know if it's related, but do not use "OR" or "AND" operators, because they have a different meaning that the classic "&&" or "||". cf http://php.net/manual/en/language.operators.logical.php
So, first, replace "AND" by "&&", and "OR" by "||".
you should use the setParameter method
$query->where('id = :id')->setParameter('id', $id);
I am using CodeIgniter2 + Doctrine2, and have the following query:
$query = $this->doctrine->em->createQuery("
SELECT u
FROM ORM\Dynasties2\Characters u
WHERE u.fathersId = $key
AND u.deathDate IS NULL
AND u.isRuler = '0'
AND u.isFemale = '0'
AND u.useAI = '1'
AND u.bornDate <= $of_age
");
$sons_of_age = $query -> getResult();
And I only want to get ONE result, assuming there are any hits.
I've looked at Doctrine documentation about using ->LIMIT(1) but I have tried putting this into my query in various places, and only get errors.
Codeigniter has some functions builtin to do $query->row() but this does not seem to work - I wager because of the Doctrine integration.
Thanks!
You're looking for method Query::setMaxResults($number); Then you can use Query:getSingleResult();, but method Query:getSingleResult(); throws error if there's no record.
$query = $this->doctrine->em->createQuery("
SELECT u
FROM ORM\Dynasties2\Characters u
WHERE u.fathersId = $key
AND u.deathDate IS NULL
AND u.isRuler = '0'
AND u.isFemale = '0'
AND u.useAI = '1'
AND u.bornDate <= $of_age
");
$query->setMaxResults(1);
try {
$sons_of_age = $query->getSingleResult();
} catch (\Doctrine\ORM\NoResultException $e) {
$sons_of_age = null;
}
$q = $this->_em->createQuery("SELECT s FROM app\models\Quest s
LEFT JOIN s.que c
WHERE s.type = '$sub'
AND c.id = '$id'");
Given a query like the one above, how would I retrieve the number of results?
Alternatively one can look at what Doctrine Paginator class does to a Query object to get a count (this aproach is most probably an overkill though, but it answers your question):
public function count()
{
if ($this->count === null) {
/* #var $countQuery Query */
$countQuery = $this->cloneQuery($this->query);
if ( ! $countQuery->getHint(CountWalker::HINT_DISTINCT)) {
$countQuery->setHint(CountWalker::HINT_DISTINCT, true);
}
if ($this->useOutputWalker($countQuery)) {
$platform = $countQuery->getEntityManager()->getConnection()->getDatabasePlatform(); // law of demeter win
$rsm = new ResultSetMapping();
$rsm->addScalarResult($platform->getSQLResultCasing('dctrn_count'), 'count');
$countQuery->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, 'Doctrine\ORM\Tools\Pagination\CountOutputWalker');
$countQuery->setResultSetMapping($rsm);
} else {
$countQuery->setHint(Query::HINT_CUSTOM_TREE_WALKERS, array('Doctrine\ORM\Tools\Pagination\CountWalker'));
}
$countQuery->setFirstResult(null)->setMaxResults(null);
try {
$data = $countQuery->getScalarResult();
$data = array_map('current', $data);
$this->count = array_sum($data);
} catch(NoResultException $e) {
$this->count = 0;
}
}
return $this->count;
}
You can either perform a count query beforehand:
$count = $em->createQuery('SELECT count(s) FROM app\models\Quest s
LEFT JOIN s.que c
WHERE s.type=:type
AND c.id=:id)
->setParameter('type', $sub);
->setParameter('id', $id);
->getSingleScalarResult();
Or you can just execute your query and get the size of the results array:
$quests = $q->getResult();
$count = count($quests);
Use the first method if you need the count so that you can make a decision before actually retrieving the objects.