how to apc case doctrine prepare query in symfony2 - symfony

I used followed query in symfony2 i need to APC cache with doctrine how to use it... I tried follow apc cache but not got error.
$query = $this->getDoctrine()->getEntityManager()->getConnection()->prepare(
"SELECT V.id,
(CASE WHEN "DAY" THEN DATE_ADD( NOW() , INTERVAL start_date DAY )
WHEN "MONTH" THEN DATE_ADD( NOW() , INTERVAL start_date MONTH )
WHEN "YEAR" THEN DATE_ADD( NOW() , INTERVAL start_date YEAR )
END as startDate
) `enter code here`
FROM table_name V
WHERE V.id = :id
ORDER BY date ASC"
);
$query->bindValue('id', $id)
$query->setResultCacheDriver(new ApcCache())
$query->useResultCache(true, 300, 'testcache');
$query->execute();
$results = $query->fetchAll();

use Doctrine\ORM\Query\ResultSetMapping;
$oResultSetMapp = new ResultSetMapping;
$oResultSetMapp->addScalarResult('id', 'id');
$oResultSetMapp->addScalarResult('name', 'name');
$sqlQuery = "SELECT T.id AS id, T.enable, T.name
FROM table_name as T
WHERE T.enable = :enable";
$query = $this->getDoctrine()->getEntityManager()
->createNativeQuery($sqlQuery, $oResultSetMapp)
->setParameter('enable', 1)
->setResultCacheDriver(new ApcCache())
->useResultCache(true, 300, 'testcache');
$query->getResult();
Try this one, this will help you for sure.

Related

Get ACF repeater field values from all posts, sorted by a sub-field

I have an ACF repeater field (publications) with 2 sub-fields.
title and year.
I need to select from the database all titles from all posts matching a condition (let’s say all titles which include ‘search-term’) but I need the result sorted by the year (the 2nd sub-field).
This is the query I use to fetch the titles.
function get_search_results(): array
{
global $wpdb;
$sql = "SELECT pm.meta_value title, pm.post_id post
FROM {$wpdb->posts} p
JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id
WHERE p.post_status = 'publish'
AND pm.meta_key LIKE 'publication_%_title'
AND pm.meta_value LIKE '%search-term%';";
return $wpdb->get_results($sql, ARRAY_A);
}
How can I sort the results by the year?
This is the solution I came up with.
Only 2 SQL queries.
function get_search_results(): array
{
global $wpdb;
// Get publication titles.
$sql = "SELECT pm.meta_key, pm.meta_value title, pm.post_id researcher
FROM {$wpdb->posts} p
JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id
WHERE p.post_status = 'publish'
AND pm.meta_key LIKE 'publication_%_title'
AND pm.meta_value LIKE '%search-term%';";
$titles = $wpdb->get_results($sql, ARRAY_A);
// Get list of post IDs.
$researcher_ids = implode(', ', array_unique(array_column($titles, 'researcher')));
// Get publication years.
$sql = "SELECT REPLACE(pm.meta_key,'_year','_title') AS meta_key, pm.meta_value year, pm.post_id researcher
FROM {$wpdb->posts} p
JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id
WHERE p.post_status = 'publish'
AND pm.meta_key LIKE 'publication_list_%_year'
AND pm.post_id IN ($researcher_ids);";
$years_raw = $wpdb->get_results($sql, ARRAY_A);
$years = [];
// Reformat the publication years.
foreach ($years_raw as $year) {
$years[$year['researcher'] . '__' . $year['meta_key']] = $year['year'];
}
// Add the year field to each title.
foreach ($titles as &$title) {
$title['year'] = $years[$title['researcher'] . '__' . $title['meta_key']];
}
// Sort the array by the inner year value.
usort($titles, 'sortByInnerYear');
return $titles;
}
function sortByInnerYear($a, $b): int
{
return $b['year'] <=> $a['year'];
}

Use placeholders and $wpdb->prepare(); found interpolated variable $now

I have a problem with placeholders in $wpdb->get_results. With the code below I have all the results correctly but I have an error when I use the code sniffer
$now = current_time('mysql', true);
$allPosts = $wpdb->get_results("
SELECT DISTINCT
YEAR(post_date_gmt) AS `year`,
MONTH(post_date_gmt) AS `month`,
MAX(post_date_gmt) AS last_mod,
count(ID) AS posts
FROM
$wpdb->posts
WHERE
post_date_gmt < '$now'
AND post_status = 'publish'
AND post_type = 'post'
GROUP BY
YEAR(post_date_gmt),
MONTH(post_date_gmt)
ORDER BY
post_date_gmt DESC
");
I tried to change with %s and $now in the end but no results are shown
$allPosts = $wpdb->get_results("
SELECT DISTINCT
YEAR(post_date_gmt) AS `year`,
MONTH(post_date_gmt) AS `month`,
MAX(post_date_gmt) AS last_mod,
count(ID) AS posts
FROM
$wpdb->posts
WHERE
post_date_gmt < %s
AND post_status = 'publish'
AND post_type = 'post'
GROUP BY
YEAR(post_date_gmt),
MONTH(post_date_gmt)
ORDER BY
post_date_gmt DESC
", $now);
I know I can resolve it by omitted post_date_gmt < %s but I'd like to know how I can resolve it with post_date_gmt < %s?

how to make this in doctrine2

I need to make a sql query like this,
UPDATE org_mapping SET is_active = 1 WHERE (org_id = ? AND service_provider_id = ? )OR (org_id = ? AND service_provider_id = ?)
I tried this but its now working:
$q = $qb->update('Organization\Entity\OrgMapping', 'om')
->set('om.active', $qb->expr()->literal($isActive))
->where('om.organization = ?1')->andWhere('om.serviceProvider = ?2')
->orWhere('om.organization = ?2')->andWhere('om.serviceProvider = ?1')
->setParameter(1, $organizationId)
->setParameter(2, $hspId)
->getQuery();
When i am running, i am getting the following query:
UPDATE org_mapping SET is_active = 1 WHERE ((org_id = ? AND service_provider_id = ?) OR org_id = ?) AND service_provider_id = ?
Replace
->orWhere('om.organization = ?2')->andWhere('om.serviceProvider = ?1')
With
->orWhere('om.organization = ?2 AND om.serviceProvider = ?1')
Try this:
$q = $qb->update('Organization\Entity\OrgMapping', 'om')
->set('om.active', $qb->expr()->literal($isActive))
->where(
$qb->expr()->orX(
$qb->expr()->andX(
$qb->expr()->eq('om.organization', '?1')
,
$qb->expr()->eq('om.serviceProvider','?2')
),
$qb->expr()->andX(
$qb->expr()->eq('om.organization', '?2')
,
$qb->expr()->eq('om.serviceProvider','?1')
)
)
)
->setParameter(1, $organizationId)
->setParameter(2, $hspId)
->getQuery();
You should not do it.
If you do an UPDATE query, you're missing the whole point of using Doctrine, that is mapping objects to database rows, not just an abstraction to queries.
Instead, extract your objects, then do a cycle and perform actions on single objects, then flush after the cycle.

ZF2 Doctrine with Symfony < OR null query

How do I write this "WHERE" condition in a way which is compatible with Doctrine?
( ( `translations_es_google`.`translation_date` < `translations_masters`.`translation_date` ) OR ( `translations_es_google`.`translation_date` is null ) )
What I have tried (unsuccessfully) are:
$query1
->andWhere('((t.translationDate < m.translationDate) OR (t.translationDate is NULL))');
$query1
->andWhere('(t.translationDate < m.translationDate) OR (t.translationDate is NULL)');
Table alias for the Doctrine query are
t represents the table translations_es_google
m represents the table translations_masters
When I remove this "andWhere" condition the rest of the QueryBuilder query executes as expected.
The query I am trying to execute is
SELECT
`translations_masters`.`translation_key` , `translations_masters`.`text_domain` , `translations_masters`.`translation_date`
FROM
`translations_masters`
LEFT JOIN
`translations_es_google` ON ( ( `translations_masters`.`text_domain` = `translations_es_google`.`text_domain` ) AND ( `translations_masters`.`translation_key` =`translations_es_google`.`translation_key` ) )
WHERE
`translations_masters`.`language_iso` NOT LIKE 'es-Google' AND ( ( `translations_es_google`.`translation_date` < `translations_masters`.`translation_date` ) OR ( `translations_es_google`.`translation_date` is null ) )
GROUP BY
`translations_masters`.`translation_key` , `translations_masters`.`text_domain`
ORDER BY
`translations_masters`.`translation_date` ASC
As requested the QueryBuilder version of this query is:
$query1 = $this->entityManager
->createQueryBuilder()
->select('m.textDomain , m.translationKey , m.translationDate , m.translationDate AS translationMasterDate , t.translationDate')
->from(
'AMDatabase\Entity\TheVerse\Translations' . $explode1 . $explode2,
't'
)
->leftJoin(
'AMDatabase\Entity\TheVerse\TranslationsMasters',
'm',
Join::WITH,
'(m.textDomain = t.textDomain) AND (m.translationKey = t.translationKey)'
)
->groupBy('m.textDomain , m.translationKey')
->orderBy(
'm.translationDate',
'ASC'
)
->setMaxResults('1');
$query1
->andWhere(
$query1->expr()
->notLike(
'm.languageIso',
':languageIso'
)
)
->setParameter(
'languageIso',
$value
);
$query1->andWhere(
$query1->expr()->orX(
't.translationDate < m.translationDate',
't.translationDate IS NULL'
)
);
$result1 = $query1->getQuery()
->getArrayResult();
The output of $query1->getQuery()->getSQL() is
SELECT
t0_.text_domain AS text_domain_0, t0_.translation_key AS translation_key_1, t0_.translation_date AS translation_date_2, t0_.translation_date AS translation_date_3, t1_.translation_date AS translation_date_4
FROM
thev1010_theverseoftheday.translations_es_google t1_
LEFT JOIN
thev1010_theverseoftheday.translations_masters t0_ ON ((t0_.text_domain = t1_.text_domain) AND (t0_.translation_key = t1_.translation_key))
WHERE
t0_.language_iso NOT LIKE ? AND (t1_.translation_date < t0_.translation_date OR t1_.translation_date IS NULL)
GROUP BY
t0_.text_domain, t0_.translation_key
ORDER BY
t0_.translation_date ASC
LIMIT 1
The ? value is 'es-Google'
The output of $query1->getQuery()->getDQL(); is
SELECT
m.textDomain , m.translationKey , m.translationDate , m.translationDate AS translationMasterDate , t.translationDate
FROM
AMDatabase\Entity\TheVerse\TranslationsEsGoogle t
LEFT JOIN
AMDatabase\Entity\TheVerse\TranslationsMasters m WITH (m.textDomain = t.textDomain) AND (m.translationKey = t.translationKey)
WHERE
m.languageIso NOT LIKE :languageIso AND (t.translationDate < m.translationDate OR t.translationDate IS NULL)
GROUP BY
m.textDomain , m.translationKey
ORDER BY
m.translationDate ASC
The ? value is 'es-Google'
How about orX expression?
You can try it this way:
$query1->andWhere(
$query1->expr()->orxX(
't.translationDate < m.translationDate',
't.translationDate IS NULL'
)
);
orX gives you the ability to add multiple conditions, separated by comma.
You can also separate your orX condition to its own variable and pass everything added to it to andWhere condition.

Wordpress Custom Query String

I have a meta field called date & I need to query all records where that timestamp is equal to or less than today...
<?php
$time = time();
$querystr = "
SELECT wposts.*
FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta
WHERE wpostmeta.meta_key = 'date'
AND wpostmeta.meta_value <= $time
";
$pageposts = $wpdb->get_results($querystr, OBJECT);
?>
You could try something like this :
$today = date('Y-m-d');
$querystr = "
SELECT *
FROM wp_posts, wp_postmeta
WHERE wp_posts.ID = wp_postmeta.post_id
AND wp_postmeta.meta_key = 'date'
AND wp_posts.post_status = 'publish'
AND wp_posts.post_type = 'post'
AND STR_TO_DATE(wp_postmeta.meta_value, '%Y/%m/%d') <= '$today'
ORDER BY STR_TO_DATE(wp_postmeta.meta_value, '%Y/%m/%d') ASC
";
$custom_loop = $wpdb->get_results($querystr, OBJECT);
In the last two lines of the que query, you have to specify the format of your date (in your custom field "date"). For example if your custom "date" field has a dd/mm/YYYY format you would use :
AND STR_TO_DATE(wp_postmeta.meta_value, '%d/%m/%Y') <= '$today'
ORDER BY STR_TO_DATE(wp_postmeta.meta_value, '%d/%m/%Y') ASC
The $today date has to be Y-m-d because it's the default time format, used for the comparison by mysql.

Resources