Doctrine 2: how do you use a subquery column (in the SELECT clause) - doctrine-orm

I'm trying to do a simple select query with a subquery in the SELECT clause and have simply not found a way to do it. I've tried with both DQL and with the QueryBuilder, neither work. The code follows, please don't say I could just use a join, this is a simplified example just to illustrate the problem, I have legitimate use cases for subqueries.
// With QueryBuilder
$query = $qb->select(array('a',
'(SELECT at.addresstypeName
FROM e:Addresstype at
WHERE at.addresstypeId = a.addresstypeId
) AS addresstypeName'))
->from('e:Address', 'a')
->where('a.addressId = :addressId')
->setParameter('addressId', 1);
// With DQL
$dql = "SELECT a,
(SELECT at.addresstypeName
FROM e:Addresstype at
WHERE at.addresstypeId = a.addresstypeId
) AS addresstypeName
FROM e:Address a
WHERE a.addressId = :addressId";
$query = $em->createQuery($dql)->setParameter(':addressId', 1);
The following relationship is defined on the Address table:
/**
* #ORM\ManyToOne(targetEntity="Addresstype")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="addresstype_id", referencedColumnName="addresstype_id")
* })
*/
protected $addresstype;
In native SQL, the query would look like this:
SELECT
a.*,
(
SELECT at.addresstype_name
FROM addresstype at
WHERE at.addresstype_id = a.addresstype_id
) AS addresstype_name
FROM address a
WHERE a.address_id = 1
Any ideas?

$query = $qb->select('a')
->addSelect('(SELECT at.addresstypeName
FROM e:Addresstype at
WHERE at.addresstypeId = a.addresstypeId) AS addresstypeName'
)
->from('e:Address', 'a')
->where('a.addressId = :addressId')
->setParameter('addressId', 1);

For me subquery with doctrine works with this query :
$qb->select('e.field')
->addSelect('(SELECT count(mv.nm)
FROM Clt\Bundle\MyBundle\Entity\MV mv
LEFT JOIN Clt\Bundle\MyBundle\Entity\M ma WITH mv.nm=ma.nm
WHERE mv.ne=e.ne and ma.nm is null
) AS nm'
)
->from($this->_entityName, 'e')
->leftJoin('e.m', 'm')
->where($qb->expr()->eq('t.id'.$typeModule, $idElementModule));
Note that in the left join you must use WITH instead of ON...

I know this is an old question, but if you want, you could have used another query builder as your subquery:
$qb->select("a")
->addSelect("(" . $qb2->select("at.addresstypeName")
->from("e:Addresstype", "at")
->where("at.addresstypeId = a.addresstypeId")
->getDQL() . ") AS addresstypeName"
)
->from('e:Address', 'a')
->where('a.addressId = :addressId')
->setParameter('addressId', 1);

In my scenario what I needed was to look into a join and find an Id and use it as boolean, found 1 otherwise 0, then applying this to orderBy. DQL expressions worked only when combined with Where clause, which wasn't my case. So, a DQL subselect saved me.
Adapted more or less to your scenario, it would look like this:
// With QueryBuilder
// In AddressRepository
// Where one address may belong to several addressTypes
public function getWithType($addressType){
$qb = $this->createQueryBuilder('a1');
$qb->addSelect('a1.someField', 'a1.otherField')
$qb->addSelect(
'(SELECT at.addressTypeName
FROM App\Entity\Address a2
JOIN a2.addressType at
WHERE at.id = '.$addressType.' AND a2.id = a1.id
) AS addressTypeName')
//The rest part of the query
}

Related

Is it possible to create an inner join between two tables showing all B that contain A?

I have two tables: Kanji, and Vocabulary. Imagine the kanji table looks like this:
目
一
人
And the vocabulary table looks like this:
目的
一番目
一人
二人
人々
注目
目標
一匹
I want to generate a table that finds all vocabulary which contains the kanji in the kanji table and list them together. So the end result would look like this:
人 一人
二人
人々
一 一人
一番目
一匹
目 目的
一番目
注目
目標
I'm not sure how to go about this. If I have just one kanji, I can use the QUERY function to generate all of the vocabularies which contain that one kanji. But can I create a dynamic table which essentially inner joins the "kanji" and "vocabulary" tables, looking for every instance of "vocabulary" contains "kanji"?
I tried using a QUERY to combine the two tables, but it won't work because the tables are mismatched in size:
=QUERY({C1:C296,D1:D224}, "SELECT Col2 WHERE Col1 contains Col2")
In the above example, the C column / Col2 is vocabulary, the D column / Col1 is kanji.
Is there a way to do this using Google Sheets?
The simplest workaround is to get intersections by 1 value:
=FILTER(D:D;REGEXMATCH(D:D;"目"))
The picture shows how to use the copy of this function to get all intersections
The other approach is to use big array-formula like:
=TRANSPOSE(SPLIT(TEXTJOIN(",";1;TRANSPOSE(ARRAYFORMULA(IF(REGEXMATCH(A1:A8;TRANSPOSE(B1:B3));A1:A8;))));","))
=ARRAYFORMULA(SORT(TRIM(SPLIT(TRANSPOSE(SPLIT(QUERY(TRANSPOSE(QUERY(TRANSPOSE(
IF(IFERROR(REGEXEXTRACT(IFERROR(REGEXEXTRACT(C1:C, REPT("(.)", LEN(C1:C)))),
TEXTJOIN("|", 1, A1:A)))<>"", "♦"&IFERROR(REGEXEXTRACT(IFERROR(
REGEXEXTRACT(C1:C, REPT("(.)", LEN(C1:C)))), TEXTJOIN("|", 1, A1:A)))&"♣"&C1:C, ))
,,999^99)),,999^99), "♦")), "♣"))))
seriously, much better way, just add a custom function:
/**
* inner join on equality
*
* #param {Range} items1 Table 1
* #param {Range} items2 Table 2
* #param {Integer} ix1 0-based index of key in Table1
* #param {Integer} ix2 0-based index of key in Table2
*
* #customfunction
* #author marc meyer (marqueymarc)
*/
function innerJoinEQ(items1 = [[]], items2 = [[]], ix1= 0, ix2= 0) {
var res = [];
var item2ix = 0;
var map = new Map();
items1 = Array.isArray(items1)? items1: [[items1]];
items2 = Array.isArray(items2)? items2: [[items2]];
items2.forEach((item2) => {
let entries = map.get(item2[ix2]) || [];
entries.push(item2);
map.set(item2[ix2], entries);
});
items1.forEach((item1) => {
let entries = map.get(item1[ix1]) || [];
entries.forEach((rightPart) => {
let cp = rightPart.slice();
cp.splice(ix2, 1);
res.push([...item1, ...cp]);
})
});
return res;
}

Doctrine 2 how to increment a column for multiple rows at once?

i'm looking for a way to increment a value for multiple rows at once without looping , is it possible in doctrine ?
here is the query in simple sql :
$sql = "UPDATE table set compteur = compteur + 1 where id in ('1','2','3') ";
using doctrine for updating many rows ( not incrementing ) , i have this :
$qb = $this->getEntityManager()->createQueryBuilder();
$query = $qb->update('Application\Entity\Table', 'l')
->set('l.compteur', $qb->expr()->literal('8'))
->where("l.id in ('$ids')")
->getQuery();
$retour = $query->execute();
Thanks for any idea !!
Use DQL for this:
$this->getEntityManager()->createQuery('
UPDATE Application\Entity\Table t
SET t.compteur = t.compteur + 1
')
->execute();
http://doctrine-orm.readthedocs.org/projects/doctrine-orm/en/latest/reference/batch-processing.html#dql-update
You can also do it with the querybuilder like so:
$qb->set('l.compteur', $qb->expr()->sum('l.compteur', 1));

spring-data Specification and joined subquery

I have the following Named query on my spring-data repository:
#Query("FROM Pedido p JOIN FETCH p.status ps WHERE ps.status IN (?1) AND ps.id IN (SELECT MAX(ps2.id) FROM PedidoStatus ps2 GROUP BY ps2.pedido)")
I'm trying to achieve the same result using the Criteria API and spring-data Specifications, this is what I have so far:
public static Specification<Pedido> byUltimoStatus(final List<PedidoStatus.StatusPedido> ultimoStatus) {
return new Specification<Pedido>() {
public Predicate toPredicate(Root<Pedido> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
Expression<PedidoStatus.StatusPedido> status = root.join("status").get("status");
Predicate predicateByStatus = status.in(ultimoStatus);
final Subquery<Long> subQuery = query.subquery(Long.class);
final Root<PedidoStatus> ps = subQuery.from(PedidoStatus.class);
Expression<Long> psId= ps.get("id");
Expression<Long> maxId = builder.max(psId);
subQuery.select(maxId);
subQuery.groupBy(ps.get("pedido").get("id"));
Predicate predicateByUltimoStatus = builder.in(root.join("status").get("id")).value(subQuery);
return builder.and(predicateByStatus, predicateByUltimoStatus);
}
};}
It's still not working, looks like there is an extra
INNERJOIN PedidoStatus
in the result query.
This is the result of the #Query:
select ... from Pedido pedido0_ inner join PedidoStatus status1_ on pedido0_.id=status1_.pedido where (status1_.status in (? , ?)) and (status1_.id in (select max(pedidostat2_.id) from PedidoStatus pedidostat2_ group by pedidostat2_.pedido))
And this is the result of the Criteria API:
select ... from Pedido pedido0_ inner join PedidoStatus status1_ on pedido0_.id=status1_.pedido inner join PedidoStatus status2_ on pedido0_.id=status2_.pedido where (pedido0_.id is not null) and status1_.status IN (?, ?) and (status2_.id in (select max(pedidostat3_.id) from PedidoStatus pedidostat3_ group by pedidostat3_.pedido))
Knowing that this is a very old question, it looks to me like the reason for the duplicate INNERJOIN in the query generated by a CriteriaQuery is that the code building the query, does actually invoke root.join("status") twice. The result of the first invocation should be saved into a local variable, so you can reuse it, instead of joining twice.
First you do:
Expression<PedidoStatus.StatusPedido> status = root.join("status").get("status");
And later you do:
Predicate predicateByUltimoStatus = builder.in(root.join("status").get("id")).value(subQuery);

Stop fetching an association

I perform a simple query like this to fetch an association with episodes:
$query = $this->getEntityManager()
->createQuery('
SELECT p,e
FROM AcmeDemoBundle:Place p
LEFT JOIN p.episodes e
WHERE p.id = :id'
)
->setParameter('id',$id);
This is a simple asso:
/**
* #ORM\OneToMany(targetEntity="Episode", mappedBy="place")
*/
protected $episodes;
This works well. Now, I don't want to fetch episodes, but simply the place object (and nothing else):
$query = $this->getEntityManager()
->createQuery('
SELECT p
FROM AcmeDemoBundle:Place p
LEFT JOIN p.episodes e
WHERE p.id = :id'
)
->setParameter('id',$id);
This is still loading episodes by lazy-loading. Is there a way to avoid lazy-loading in that case?
Many thanks.
Like this:
$query = $this->getEntityManager()
->createQuery('
SELECT p
FROM AcmeDemoBundle:Place p
WHERE p.id = :id'
)
->setParameter('id',$id);
$query->setHint(Query::HINT_FORCE_PARTIAL_LOAD, true);

conversion sql query to jpa

I have a query
SELECT d.name, count(e.id) FROM department d LEFT OUTER JOIN employee e on e.department_id = d.id and e.salary > 5000
and how i can convert this to jpa
right now i have:
CriteriaQuery<Object[]> criteria = builder.createQuery(Object[].class);
Root<Department> root = criteria.from(Department.class);
Path<String> name = root.get("name");
Expression<Long> empCount = builder.count(root.get("employees").get("id"));
criteria.multiselect(name,empCount);
TypedQuery<Object[]> query = em.createQuery(criteria);
I simplified both examples by removing ordering and grouping
can anyone tell me how i can modifie my jpa code to get same reslults like from my sql query
thanks in advance
You're not far from the result. The problem is that, AFAIK, you can't add any restriction on the on clause, using JPA. So the query wil have to be rewritten as
SELECT d.name, count(e.id) FROM department d
LEFT OUTER JOIN employee e on e.department_id = d.id
where (e.id is null or e.salary > 5000)
Here is the equivalent of this query not tested):
CriteriaQuery<Object[]> criteria = builder.createQuery(Object[].class);
Root<Department> root = criteria.from(Department.class);
Path<String> name = root.get("name");
Join<Department, Employee> employee = root.join("employees", JoinType.LEFT);
Expression<Long> empCount = builder.count(employee.get("id"));
criteria.multiselect(name,empCount);
criteria.where(builder.or(builder.isNull(employee.get("id")),
builder.gt(employee.get("salary"), 5000)));
TypedQuery<Object[]> query = em.createQuery(criteria);