I can't understand why I have different results with this code:
The only thing I change token for setParameter.
The result is empty.
This works
$this->createQueryBuilder('t')
->select('t, c')
->leftJoin('t.documentos', 'c')
->where('t.flagStatus = :status')
->andWhere('c.flagStatus = :status')
->andWhere('t.idSecretaria in (:s)')
->andWhere('t.typedoc = 1')
->orderBy('c.tituloInformacao', 'ASC')
->setParameters([
'status' => true,
's' => 8,
])
->getQuery()
->execute();
But this won't work an empty result set is given.
$this->createQueryBuilder('t')
->select('t, c')
->leftJoin('t.documentos', 'c')
->where('t.flagStatus = :status')
->andWhere('c.flagStatus = :status')
->andWhere('t.idSecretaria in (:s)')
->andWhere('t.typedoc = :td')
->orderBy('c.tituloInformacao', 'ASC')
->setParameters([
'status' => true,
's' => 8,
'td' => 1,
])
->getQuery()
->execute();
Related
I would like to create an array like this , and I'm lost with the syntax:
I can't nest the arrays together
$PeriodDayWeek = Array(
[monday] => Array
(
[start] => Array(
[from] => Morninghour,
[to] => Afternoonhour,
),
[end] => Array(
[from] => Morninghour,
[to] => Afternoonhour,
)
),
[tuesday] ...
until [sunday]
)
I have the beginning but it's not good:
$PeriodDayWeek = [];
foreach($EnglishDay as $Day):
$Day = array(
"start" => array(
"from" => $_POST['Dayweek_JoMo_FrH_'. $Day] .'h'. $_POST['Dayweek_JoMo_FrM_'. $Day] ,
"to" => $_POST['Dayweek_JoMo_ToH_'. $Day] .'h'. $_POST['Dayweek_JoMo_ToM_'. $Day]
)
);
endforeach;
$PeriodDayWeek = array_merge($Day, $EnglishDay);
$events_meta['periodevent_dayweek'] = maybe_serialize($PeriodDayWeek);
Solved :
$PeriodDayWeek =array();
foreach($EnglishDay as $day){
$PeriodDayWeek[$day] = array(
"start" => array(
"from" => $_POST['Dayweek_JoMo_FrH_'. $day] .'h'.$_POST['Dayweek_JoMo_FrM_'. $day] ,
"to" => $_POST['Dayweek_JoMo_ToH_'. $day] .'h'. $_POST['Dayweek_JoMo_ToM_'. $day]
)
);
}
$events_meta['periodevent_dayweek'] = maybe_serialize($PeriodDayWeek);
How could I write this sql query on symfony query builder syntax?
Analysis, Region, Nature and Garden are Entities
SELECT * FROM `analysis`
INNER JOIN sample ON sample.id = analysis.sample_id
INNER JOIN region ON sample.region_id = region.id
INNER JOIN nature ON sample.nature_id = nature.id
INNER JOIN garden ON sample.garden_id = garden.id
WHERE sample.stateProduct = 'Origin'
AND analysis.status = '0'
AND region.name = 'Jangsu'
AND garden.name = 'North Tukvar'
AND nature.name = 'Thé Vert'
AND sample.sampleBio = '1'
AND sample.supplierCountry = 'Inde'
I tried this way but, I don't have error msg, but it's not same result as sql query.
public function countAnalysisByCriteria($stateProduct, $status, Nature $nature, Region $region, Garden $garden, $supplierName, $bio, $country, $startDate, $endDate){
$qb = $this->createQueryBuilder('analysis')
->addSelect('count(analysis) as result')
->innerJoin('analysis.sample', 'sample', 'WITH', 'analysis.sample = sample')
->innerJoin('sample.nature', 'nature', 'WITH', 'sample.nature = :nature')
->innerJoin('sample.region', 'region', 'WITH', 'sample.region = :region')
->innerJoin('sample.garden', 'garden', 'WITH', 'sample.garden = :garden')
->groupBy('result');
->andWhere('sample.stateProduct = :stateProduct');
->setParameter('stateProduct', $stateProduct);
->andWhere('sample.nature = :nature');
->setParameter('nature', $nature);
->andWhere('sample.region = :region');
->setParameter('region', $region);
->andWhere('sample.garden = :garden');
->setParameter('garden', $garden);
->andWhere('sample.dateReception BETWEEN :startDate AND :endDate');
$qb->setParameter('startDate', $startDate);
$qb->setParameter('endDate', $endDate);
}
return $qb->getQuery()->getArrayResult();
Your code snippet is completely wrong, try the following:
use Doctrine\ORM\Query\Expr\Join;
public function countAnalysisByCriteria(
$stateProduct,
$status,
Nature $nature,
Region $region,
Garden $garden,
$supplierName,
$bio,
$country,
$startDate,
$endDate
) {
$qb = $this->createQueryBuilder();
return $qb->select('count(analysis) as result')
->innerJoin('analysis.sample', 'sample', Join::WITH, 'analysis.sample = sample.id')
->innerJoin('sample.nature', 'nature', Join::WITH, 'sample.nature = nature.id')
->innerJoin('sample.region', 'region', Join::WITH, 'sample.region = region.id')
->innerJoin('sample.garden', 'garden', Join::WITH, 'sample.garden = garden.id')
->groupBy('result')
->andWhere('sample.stateProduct =:stateProduct')
->setParameter('stateProduct', $stateProduct)
->andWhere('sample.nature =:nature')
->setParameter('nature', $nature)
->andWhere('sample.region =:region')
->setParameter('region', $region)
->andWhere('sample.garden =:garden')
->setParameter('garden', $garden)
->andWhere('sample.dateReception BETWEEN :startDate AND :endDate')
->setParameter('startDate', $startDate)
->setParameter('endDate', $endDate)
->getQuery()
->getArrayResult();
}
DO NOT add spaces on assignments = : (wrong), =: (right)
Check your code properly, notice how I have removed some colon ; at some pieces because does not make sense have them there.
I'm trying to update a certain number of rows of my entity "Vehicule". I have no idea how could it work.
I'm actually trying to modify only two rows where direction= 5.This is the function I used in order to update.
public function ValidAction(\OC\UserBundle\Entity\User $direction) {
$qb = $this->getDoctrine()
->getRepository('CarPfeBundle:Vehicule')
->createQueryBuilder('v');
$q = $qb->update ('CarPfeBundle:vehicule v')
->set('v.direction', '?1')
->where('v.direction = ?2')
->setParameter(1, $direction)
->setParameter(2, 5)
->getQuery();
$p = $q->execute();
return $this->redirect($this->generateUrl('demandeveh_afficher'));
}
But the above code update all rows of my database. I need to update only two rows. Any help please?
Try to do this ;
public function ValidAction(\OC\UserBundle\Entity\User $direction) {
$qb = $this->getDoctrine()
->getRepository('CarPfeBundle:Vehicule')
->createQueryBuilder('v');
// $ids an array that contains all ids with your condition
$ids = $qb->select('v.id')
->where('v.direction = :direction')
->setParameter(
array(
'direction' => $direction
)
)
->getQuery()
->getResult();
$id1 = $ids[array_rand($ids)];
$id2 = $ids[array_rand($ids)];
//To be sure that $id1 is different from id2
while ($id1 == $id2) {
$id2 = $ids[array_rand($ids)];
}
$q = $qb->update ('CarPfeBundle:vehicule v')
->set('v.direction', ':val1')
->where('v.direction = :val2')
->andWhere('v.id IN (:id1, :id2)')
->setParameter(
array(
'val1' => $direction ,
'val2' => 5 ,
'id1' => $id1,
'id2' => $id2,
)
)
->getQuery();
$p = $q->execute();
return $this->redirect($this->generateUrl('demandeveh_afficher'));
}
With the above code I hope you can update only two rows and randomly.
Good luck !
While a solution like Houssem Zitoun suggested may work, why not use a subquery?
If you get the (like I did, if not, just skip the middle SELECT)
Error: #1235 - This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'
go with this answer and something like (doc): - untested
UPDATE CarPfeBundle:Vehicule v
SET v.direction = ?1
WHERE v.direction IN
(SELECT * FROM (
SELECT v.direction
FROM CarPfeBundle:Vehicule v2
WHERE v.direction = ?2 LIMIT 2
)) AS sq
Can someone tell me what wrong with this query.
if ( isset( $_GET['lokacija'] ) && !empty( $_GET['lokacija'] ) ) {
$lokacija = $_GET['lokacija'];
} else { $lokacija = ''; }
if ( isset( $_GET['tip'] ) && !empty( $_GET['tip'] ) ) {
$tip = $_GET['tip'];
} else { $tip = ''; }
if ( isset( $_GET['sobe'] ) && !empty( $_GET['sobe'] ) ) {
$sobe = $_GET['sobe'];
} else { $sobe = ''; }
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args2 = array(
'posts_per_page' => 10,
'post_type' => 'nekretnine',
'paged' => $paged,
if ($lokacija != '') {
'meta_query' => array(
array (
'key' => 'lokacija',
'value' => $lokacija.''
),
)
}
);
$wp_query = new WP_Query( $args2 );
This code gives me error
Parse error: syntax error, unexpected T_IF, expecting ')' in
*/wp-content/themes/gs/page-nek-pretraga.php on line 23;
Line 23 is line that starts with if ($lokacija)...
What i want to do is to use multiple meta_query that i can get from php get (www.blabla./com/page1/?lokacija=foo&tip=foo&sobe=3)
But, i want it only if lets say $lokacija is not empty. Same for other two (possible 5-6 later) fields.
You can not include if condition in array. Whatever you are trying to achieve with above code is you can achieve with this following code.
$args2 = array(
'posts_per_page' => 10,
'post_type' => 'nekretnine',
'paged' => $paged,
);
if ($lokacija != '') {
$args2['meta_query'] = array(
array (
'key' => 'lokacija',
'value' => $lokacija.''
),
);
}
To check for multiple custom fields we have to join the meta table twice.
So the copy of the table is joined with a different temporary table name.
global $wpdb; $query = " SELECT * FROM {$wpdb--->prefix}posts
INNER JOIN {$wpdb->prefix}postmeta m1
ON ( {$wpdb->prefix}posts.ID = m1.post_id )
INNER JOIN {$wpdb->prefix}postmeta m2
ON ( {$wpdb->prefix}posts.ID = m2.post_id )
WHERE
{$wpdb->prefix}posts.post_type = 'post'
AND {$wpdb->prefix}posts.post_status = 'publish'
AND ( m1.meta_key = 'date' AND m1.meta_value > '2010-12-05 00:00:00' )
AND ( m1.meta_key = 'date' AND m1.meta_value < '2010-12-12 00:00:00' ) AND ( m2.meta_key = 'some_other_meta_value' AND m2.meta_value != '' ) GROUP BY {$wpdb->prefix}posts.ID
ORDER BY {$wpdb->prefix}posts.post_date
DESC;
For More Details Visit : http://realtuts.com/write-custom-wordpress-sql-query-multiple-meta-values/
";
For a project I need to give a load of diverse data in JSON format. All the information will be used on the same page so a single call would result in the least overhead. The information all concerns the same database object and is all necessary on the page. It basically is a collection of counts of the amount of objects that are of one or more of a certain type (the types are all booleans) and we require to know a lot of different variations of this. I used the code below but my co-worker believes the way I put it in the JSON list is a bit clunky and the code could has a greater performance. How could I improve this code?
public function getContactsStatisticsAction()
{
$response = new Response();
$json = array();
$em = $this->getDoctrine()->getEntityManager();
$cr = $em->getRepository('BlaCoreBundle:Company');
$json['numberOfCompanies'] = $cr->numberOfCompanies();
$json['numberOfAccounts'] = $cr->numberOfCompanies(array("typeAccount" => true));
$json['numberOfCompetitors'] = $cr->numberOfCompanies(array("typeCompetitor" => true));
$json['numberOfSuppliers'] = $cr->numberOfCompanies(array("typeSupplier" => true));
$json['numberOfOthers'] = $cr->numberOfCompanies(array("typeOther" => true));
$json['numberOfUnassigned'] = $cr->numberOfCompanies(array("typeAccount" => false, "typeCompetitor" => false,"typeSupplier" => false,"typeOther" => false));
$json['numberOfJustAccounts'] = $cr->numberOfCompanies(array("typeAccount" => true, "typeCompetitor" => false, "typeSupplier" => false));
$json['numberOfJustCompetitors'] = $cr->numberOfCompanies(array("typeAccount" => false, "typeCompetitor" => false, "typeSupplier" => false));
$json['numberOfJustSuppliers'] = $cr->numberOfCompanies(array("typeAccount" => false, "typeCompetitor" => false, "typeSupplier" => false));
$json['numberOfCompetitorAndAccounts'] = $cr->numberOfCompanies(array("typeAccount" => true, "typeCompetitor" => true, "typeSupplier" => false));
$json['numberOfCompetitorAndSuppliers'] = $cr->numberOfCompanies(array("typeAccount" => false, "typeCompetitor" => true, "typeSupplier" => true));
$json['numberOfSupplierAndAccounts'] = $cr->numberOfCompanies(array("typeAccount" => true, "typeCompetitor" => false, "typeSupplier" => true));
$json['numberOfCompaniesAndAccountsAndSuppliers'] = $cr->numberOfCompanies(array("typeAccount" => true, "typeCompetitor" => true, "typeSupplier" => true));
$response->setContent(json_encode($json));
return $response;
}
public function numberOfCompanies($filters = array())
{
$qb = $this->getEntityManager()->createQueryBuilder();
$qb->select('count(c.id)');
$qb->from('BlaCoreBundle:Company', 'c');
$sizeFilters = count ($filters);
$keys = array_keys($filters);
if($sizeFilters >= 1){
$qb->where('c.' . $keys[0] . ' = ' . (int) $filters[$keys[0]]);
}
for($i = 1; $i < $sizeFilters; $i++){
$qb->andWhere('c.' . $keys[$i] . ' = ' . (int) $filters[$keys[$i]]);
}
return $qb->getQuery()->getSingleScalarResult();
}
Your colleagues are right. You should get all that scalar results in a single query. You will minimize the number of connections in this way.
The topic is solved in this answer for a non-Doctrine case.
Such a user also made this interesting question here, but none answered.
Actually I think that there is no way to solve this kind of query with QueryBuilder or with DQL. Also in the official docs for Doctrine2.2 there are no examples of a JOIN on a SELECT.
What you can try is something like the following DQL query:
return $this->getEntityManager()->createQuery(
SELECT COUNT(c1) AS C1, COUNT(c2) AS C2, COUNT(c3) AS C3 FROM
BlaCoreBundle:Company c1, BlaCoreBundle:Company c2, BlaCoreBundle:Company c3
WHERE c1.prop1 = 'xxx' AND c2.prop2 > '100' AND c3.prop3 LIKE '%XYZ%')
->getResult();
where of course the WHERE clauses are general examples.
This query will return a one sized array, with C1, C2 and C3 as the key for the values you counted. Of course, it becomes difficult to use JOIN and whatever you need, but you can always use WHERE IN (SELECT...) and WHERE EXISTS (SELECT...), e.g.
SELECT COUNT(c1) AS C1, COUNT(c2) AS C2, COUNT(c3) AS C3 FROM
BlaCoreBundle:Company c1, BlaCoreBundle:Company c2, BlaCoreBundle:Company c3
WHERE c1.prop1 = 'xxx' AND c2.prop2 > '100' AND c3.prop3 LIKE '%XYZ%'
AND EXISTS (SELECT x FROM BlaCoreBundle:Entity x JOIN x.company comp WHERE x.prop = "valye" AND comp = c1)