I'm trying to convert this SQL into either DQL or whatever the query builder variant would look like.
select *
from project_release r
where (select s.title as status_name
from release_status_log l
left join release_status s
on l.release_status_id = s.id
where l.release_id = r.id
order by l.created_at desc
limit 1
) not in ('Complete', 'Closed')
;
From inside the repository class for the Release entity, I've tried this
return $this->getEntityManager()->createQuery("
select r.*
from MyBundle:Release r
where (select s.title
from MyBundle:ReleaseStatusLog l
join l.status s
where l.release = r
order by l.createdAt desc
limit 1
) IN ('Complete','Closed')
order by r.release_date ASC
limit 10
")->getArrayResult();
Which gives the error
[Syntax Error] line 0, col 265: Error: Expected
Doctrine\ORM\Query\Lexer::T_CLOSE_PARENTHESIS, got 'limit'
Which is referring to the limit 1 in the subquery.
So then I tried this
return $this
->createQueryBuilder('r')
->select('r.*')
->where("(select s.title
from MyBundle:ReleaseStatusLog l
join l.status s
where l.release = r
order by l.created_at desc
limit 1
) $inClause ('Complete', 'Closed')
")
->setMaxResults( $limit )
->orderBy('release_date', 'ASC')
->getQuery()
->getArrayResult()
;
Which gives the same error. How can I execute a subquery limited to 1 row per row in the parent query?
Symfony 2.0.15
Doctrine 2.1.7
PHP 5.3.3
MySQL 5.1.52
I have a solution for this now. I ended up falling back on the native query system with the result set mapping from the entity in questions.
It's not a great solution, but it works and until I see another solution, it's the only option with this type of WHERE clause.
Here's what my finder method looks like now
/**
* Finds Releases by their current status
*
* #param array $statuses White-list of status names
* #param boolean $blackList Treat $statuses as a black-list
* #param integer $limit Limit the number of results returned
* #param string $order Sort order, ASC or DESC
*
* #throws \InvalidArgumentException
*
* #return array <Release>
*/
public function findByCurrentStatus( array $statuses, $blackList=false, $limit=null, $order='ASC' )
{
if ( empty( $statuses ) )
{
throw new \InvalidArgumentException( "Must provide at least one status" );
}
$inClause = $blackList ? 'not in' : 'in';
$rsm = new ResultSetMappingBuilder($this->getEntityManager());
$rsm->addRootEntityFromClassMetadata('MyBundle:Release', 'r');
$SQL = "
select *
from project_release r
where (select s.title as status_name
from release_status_log l
left join release_status s
on l.release_status_id = s.id
where l.release_id = r.id
order by l.created_at desc
limit 1
) $inClause ('" . implode( "','", $statuses ) . "')
order by r.release_date $order
";
if ( $limit )
{
$SQL .= " limit $limit";
}
return $this
->getEntityManager()
->createNativeQuery( $SQL, $rsm )
->getResult()
;
}
I kind of loathed going back to building a query as a string, but oh well. Oh, and for you eagle-eyes, $statuses does not come from user data, so no SQL injection vulnerabilities here ;)
In addition to your Native SQL solution, you can create two queries using DQL within a single repository method.
Some adjustment may be required but you could try this:
public function findCompletedReleases()
{
$em = $this->getEntityManager();
$dqlSubQuery = <<<SQL
SELECT
s.title status_name
FROM
Acme\MyBundle\Entity\ReleaseStatus s,
Acme\MyBundle\Entity\ReleaseStatusLog l,
Acme\MyBundle\Entity\Release r
WHERE
l.release = r.id AND
l.status = s.id
ORDER BY l.createdAt DESC
SQL;
$statusName = $em->createQuery($dqlSubQuery)
->setMaxResults(1)
->getSingleScalarResult();
$dql = <<<SQL
SELECT
r
FROM
Acme\MyBundle\Entity\Release r
WHERE
:status_name IN ('Complete','Closed')
ORDER BY r.release_date ASC
SQL;
$q = $em->createQuery($dql)
->setParameters(array('status_name' => $statusName))
->setMaxResults(10);
return $q->getArrayResult();
}
Related
I've created two entities called Project and ProjectTag using Doctrine (doctrine/orm v2.6.1) and Symfony. I'd like to select all projects that have all tags with the names given in $tags. The following query from my ProjectRepository.php works in my dev environment with SQLite:
public function findByAllTags($tags)
{
$queryBuilder = $this->createQueryBuilder('p');
for ($i = 0; $i < count($tags); $i++) {
$tagSubQueryBuilder = $this->createQueryBuilder("p$i")
->join('p.tags', "tags_joined_$i")
->andWhere("tags_joined_$i.name = ?$i");
$queryBuilder->andWhere(
$queryBuilder->expr()->exists($tagSubQueryBuilder->getDQL())
);
}
$queryBuilder->orderBy('p.timeCreated','DESC');
return $queryBuilder->getQuery()->setParameters($tags)->getResult();
}
This gets converted to
SELECT
p0_.id AS id_0,
p0_.name AS name_1
FROM
project p0_
WHERE
(
EXISTS (
SELECT
p1_.id
FROM
project p1_
INNER JOIN projects_tags p3_ ON p0_.id = p3_.project_id
INNER JOIN project_tag p2_ ON p2_.id = p3_.project_tag_id
WHERE
p2_.name = ?
)
)
ORDER BY
p0_.created DESC
However, in my production environment with MySQL I get the following error:
An exception occurred while executing 'SELECT p0_.id AS id_0, p0_.name AS name_1 FROM project p0_ WHERE (EXISTS (SELECT p1_.id FROM project p1_ INNER JOIN projects_tags p3_ ON p0_.id = p3_.project_id INNER JOIN project_tag p2_ ON p2_.id = p3_.project_tag_id WHERE p2_.name = ?)) ORDER BY p0_.created DESC' with params ["video"]:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'p0_.id' in 'on clause'
In response to your comment, this is an untested approach to your problem without nested queries:
public function findAllByTags($tags)
{
$qb = $this->createQueryBuilder('p');
$qb->join('p.tags', 't');
$qb->where($qb->expr()->in('t.name', ':tags'));
$qb->groupBy('p.id');
$qb->having($qb->expr()->eq('COUNT(t.id)', ':count'));
$qb->setParameter('tags', $tags);
$qb->setParameter('count', count($tags));
return $qb->getQuery()->getResult();
}
This assumes you pass the tag names as an array (or that the Tag class implements a __toString() method that returns the tags name).
I'm trying to do a reviews plugin in Wordpress, and one of the thing that my client asked me to do was that a user should be able to rate only one product every 24 horas, so I have to establish a limit between rates.
And I made this function to check if the limit is reached:
function isAllowedToRate(){
global $wpdb;
$currentDate = date('Y-m-d');
$userId = get_current_user_id();
$table_name = $wpdb->prefix .'esvn_reviews';
$isAllowed = $wpdb->get_results(
"
SELECT user_id, fecha_calificacion
FROM {$table_name}
WHERE user_id = {$userId}
AND review_date = {$currentDate}
"
);
if( count( $isAllowed > 0 ) ){
return false;
}else{
return true;
}
}
But every time I try to run it, it returns false, the error that I'm getting from Wordpress is this:
<div id='error'>
<p class='wpdberror'><strong>WordPress database error:</strong> []<br />
<code>
SELECT user_id, fecha_calificacion
FROM wp_esvn_reviews
WHERE user_id = 6
AND fecha_calificacion = 2015-10-30
</code></p>
</div>
If I take the same SQL and run it directly into the database, it works like a charm, but I keep getting this error from Wordpress and the function always returns false.
You need to wrap your date in single quotes.
$isAllowed = $wpdb->get_results(
"
SELECT user_id, fecha_calificacion
FROM {$table_name}
WHERE user_id = {$userId}
AND review_date = '{$currentDate}'
"
);
Alternatively you could use $wpdb->prepare(), which I would consider better form.
$sql = <<<SQL
SELECT user_id, fecha_calificacion
FROM {$table_name}
WHERE
user_id = %d -- this is formatted as a (d)igit
AND review_date = %s -- this is formatted as a (s)tring
SQL;
$isAllowed = $wpdb->get_results($wpdb->prepare($sql, $userId, $currentDate));
I found the error (in case someone needs the information in the future), I was treating $isAllowed as an array, and it was an object, I had to add ARRAY_A to the get_results:
$isAllowed = $wpdb->get_results(
"
SELECT user_id, fecha_calificacion
FROM {$table_name}
WHERE user_id = {$userId}
AND review_date = {$currentDate}
",ARRAY_A /* output as an associative array */
);
I am really new at Symfony and I am trying to get used to query builder. At the moment I am trying to join three tables and the following MySQL query gives me the results I need when I run it in PhpMyAdmin
SELECT * FROM pe_users u
LEFT JOIN pe_apply a ON u.id = a.user
LEFT JOIN pe_offer o ON a.id = o.application
However when I move this inside a Symfony Repository method
namespace Ache\AdminBundle\Repository;
use Doctrine\ORM\EntityRepository;
class AdminRepository extends EntityRepository{
public function findAllAppByStatus(){
$query = $this->getEntityManager()->createQuery(
'SELECT * FROM pe_users u
LEFT JOIN pe_apply a ON u.id = a.user
LEFT JOIN pe_offer o ON a.id = o.application
');
try {
return $query->getSingleResult();
} catch (\Doctrine\ORM\NoResultException $e) {
return null;
}
}
}
I get the error
[Syntax Error] line 0, col 7: Error: Expected IdentificationVariable |
ScalarExpression | AggregateExpression | FunctionDeclaration |
PartialObjectExpression | "(" Subselect ")" | CaseExpression, got '*'
What does this error mean? what am I doing wrong?
UPDATE
The three entities I have are as following
UserBundle:User
CoreBundle:Apply
AdminBundle:Offer
User.id links with Apply.user and Offer.application links with Apply.id
You can still use raw sql with Symfony if you are comfortable with that
$conn = $this->getEntityManager()->getConnection();
$sql = "SELECT * FROM pe_users u LEFT JOIN pe_apply a ON u.id = a.user LEFT JOIN pe_offer o ON a.id = o.application WHERE u.id = a.user";
$stmt = $conn->prepare($sql);
$stmt->execute();
return $stmt->fetchAll();
I would do :
public function findAllAppByStatus(){
$qb = $this->createQueryBuilder('u')
->leftJoin('CoreBundle:Apply', 'a', 'WITH', 'a.user = u')
->leftJoin('AdminBundle:Offer', 'o', 'WITH', 'o.application = a')
->setMaxResults(1); // if you return only 1 result, you want to be sure only one (or none) result is fetched
return $qb->getQuery()->getOneOrNullResult();
if you want to return possibly many results, as the 'All' in the method name suggests, get rid of the ->setMaxResults() and use $qb->getQuery()->getResult();
see how the queryBuilder works with objects, not tables. Joins are built on entities and properties, not tables and field names.
Building a query to select M entities that have no corresponding N entities returns an error with the following query:
return $this->getEntityManager()
->createQuery(
'SELECT p FROM VolVolBundle:Opportunity p '
. 'LEFT JOIN VolVolBundle:Volunteer v'
. 'WHERE v.id is null '
. 'ORDER BY p.organization ASC'
);
returns the error:
Expected Doctrine\ORM\Query\Lexer::T_WITH, got 'v'
Yet the following SQL statement returns a non-empty resultset:
select o.id from opportunity o
left outer join opportunity_volunteer ov on o.id = ov.opportunity_id
left outer join volunteer v on ov.volunteer_id = v.id
where ov.id is null;
where opportunity_volunteer is the linking table
Opportunity entity relationship definition
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="Volunteer", inversedBy="opportunities", cascade={"persist"})
* #ORM\JoinTable(name="opportunity_volunteer",
* joinColumns={#ORM\JoinColumn(name="opportunity_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="volunteer_id", referencedColumnName="id")}
* ))
*/
protected $volunteers;
public function addVolunteer(\Vol\VolBundle\Entity\Volunteer $volunteer) {
$volunteer->addOpportunity($this);
array_push($volunteers, $volunteer);
}
public function getVolunteers() {
return $this->volunteers;
}
Volunteer entity relationship definition
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="Opportunity", mappedBy="volunteers")
*/
protected $opportunities;
public function addOpportunity(\Vol\VolBundle\Entity\Opportunity $opportunity) {
array_push($opportunities, $opportunity);
}
public function getOpportunities() {
return $this->opportunities;
}
Reading from the DQL docs, you should use WITH instead of WHERE to limit the join. Search for the code snippet "Restricting a JOIN clause by additional conditions" in the docs. I guess it should be something like:
return $this->getEntityManager()
->createQuery(
'SELECT p FROM VolVolBundle:Opportunity p '
. 'LEFT JOIN VolVolBundle:Volunteer v'
. 'WITH v.id IS null '
. 'ORDER BY p.organization ASC'
);
This is not tested, though.
The eventual solution was to create a 1:n:1 relationship, eliminating the "invisible" entity in the middle. This enabled adding fields to the relationship. So in addition to assuring each line ended with a space character before concatenation the query needed to be rewritten. It now finds the null results as desired:
return $this->getEntityManager()
->createQuery(
'SELECT p FROM VolVolBundle:Opportunity p '
. 'LEFT JOIN VolVolBundle:OpportunityVolunteerEmail e '
. 'with p = e.opportunity '
. 'where e.opportunity is null'
. 'ORDER BY p.organization ASC'
)->getResult();
I'm trying to run this query on Propel 1.6 with symfony 1.4.20.
I want to bind 2 parameters onto this subquery but its not working.
$paginas = PaginaQuery::create()
->where("pagina.id not in (select id from cliente_artista where cliente_artista.cliente_id = ? and cliente_artista.culture = ?)"
,array('XXX', 'en')
)
->limit(5)
->find();
This gives me the error:
Cannot determine the column to bind to the parameter in clause
I also found this post but there is no answer (https://groups.google.com/forum/?fromgroups=#!topic/propel-users/2Ge8EsTgoBg)
Instead of using placeholders. You may use $id and $culture:
//first, get an array of the id's
//define your vars
$id = $your_id_param;
$culture = 'en';
$cliente_artistas = ClienteArtistaQuery::create()
->select('id')
->distinct()
->filterByClienteId($id)
->filterByCulture($culture)
->find();
$paginas = PaginaQuery::create()
->where("pagina.id NOT IN ?", $cliente_artistas)
->limit(5)
->find();
If this has to be done in one query, recommend using raw sql and binding the parameters into the PDO statement (but then you lose the convenience of PropelObjectCollections):
public function getResultSet($id, $culture) {
$id = $id_param;
$culture = $culture_param;
$sql = <<<ENDSQL
SELECT * from pagina
WHERE id NOT IN (SELECT distinct id
FROM cliente_artista
WHERE cliente_id = ?
AND culture = ?
)
LIMIT 5
ENDSQL;
$connection = Propel::getConnection();
$statement = $connection->prepare($sql);
$statement->bindValue(1, $id);
$statement->bindValue(2, $culture);
$statement->execute();
$resultset = $statement->fetchAll(PDO::FETCH_ASSOC); // or whatever you need
if (! count($resultset) >= 1) {
// Handle empty resultset
}
return $resultset;
}
You could also write some query methods to use propel orm query methods. Ofcourse, the propel api is beneficial reference. There are several ways to do this. I have indicated one method here which should work for you.
EDIT:
Here's an idea on doing this as one query [since useSelectQuery() requires 'relation' name], this idea assumes tables are not related but that id's are:
$paginas = PaginaQuery::create()
->addJoin(PaginaPeer::ID, ClienteArtistaPeer::CLIENTE_ID, Criteria::LEFT_JOIN)
->where("ClienteArtista.Id <> ?", $id)
->where("ClienteArtista.Culture <> ?", $culture)
->select(array('your','pagina','column','array'))
->limit(5)
->find();