A working application uses a native SQL query to get items from a ManyToMany Entity relationship. Attempts to translate that query end up in a myriad of error messages. The Household entity has a ManyToMany relationship with Reason. Both entities & their relationships are properly defined. The joining table (household_reason) is not defined in .../Entity. The part that eludes me is how to join the Contact entity, with which the Household entity has a OneToMany relationship.
The working SQL:
select distinct r.reason
from reason r
join household_reason hr on hr.reason_id = r.id
join household h on h.id = hr.household_id
join contact c on c.household_id = h.id...
For starters, here's the beginning of a query builder in the Reason repository:
$query = $this->createQueryBuilder('r')->select('distinct r.reason')
->innerJoin('r.households', 'h')
Now that there's the plural households, how to I specify a relationship to a singular household?
Took a while, but the following works:
$query = $this->createQueryBuilder('r')->select('distinct r.reason')
->innerJoin('r.households', 'h')
->innerJoin('TruckeeProjectmanaBundle:Contact', 'c', 'WITH c.household = h.household')
->where('c.contactDate >= :startDate')
->andWhere('c.contactDate <= :endDate')
->andWhere('r.enabled = TRUE')
->orderBy('r.id')
->setParameters($dateCriteria)
->getQuery()
->getResult();
Related
I'm pretty new to Doctrine ORM and I'm trying to transform a raw SQL query with doctrine to get an array of Entities.
Basically I want to get one of more course entities where a user is indirectly registered. The course id is in a traineeship table. The traineeship id and the user id are in a registration table.
Here's my SQL query :
SELECT * FROM course c
LEFT JOIN traineeship t
ON c.id = t.courseId
LEFT JOIN registration r
ON t.id = r.traineeshipId
WHERE r.userId = 2681;
Here's what I try to do with doctrine :
return $this->createQueryBuilder('c')
->andWhere('t.course = c')
->leftJoin('c.traineeships', 't')
->andWhere('r.traineeship = t')
->leftJoin('t.registrations', 'r')
->andWhere('r.id = :user')
->setParameter('user', $user)
->getQuery()
->execute();
With my raw SQL query, I get two expected results with a given id. With the generated query by doctrine, I get only one result. So I guess my doctrine use is bad.
(Doctrine relations :
Course OneToMany Traineeship
Traineeship OneToMany Registration
Registration ManyToOne User)
From the raw SQL I would expect the following query:
return $this->createQueryBuilder('c')
->leftJoin('c.traineeships', 't')
->leftJoin('t.registrations', 'r')
->andWhere('r.user = :user')
->setParameter('user', $user)
->getQuery()
->getResult();
Please note that I'm using ->andWhere('r.user = :user') instead of ->andWhere('r.id = :user') as I assume that registration.id holds the id of the registration but not the id of the user. In my query I furthermore assume that registration has an attribute user which holds a reference to the user.
The query should return an array of course entities.
I am implementing category filters with many to many relations in doctrine using symfony3. I have an entity Business and Category with many to many association. The new table with many to many relations looks like below
business_id category_id
1 1
1 2
2 1
2 2
3 1
Now I want to get all the businesses which are having category_id=1 and category_id=2.
It should select the business id 1,2.
My Sql Query:-
SELECT * FROM business
LEFT JOIN business_category ON business_category.business_id=business.id
WHERE business_category.category_id = 1 AND business_category.category_id = 2
Any SQL or Doctrine query would work.
I would really appreciate for any help.
To get the businesses which exists in both categories your write your query builder as follows,I assume your entities are mapped with proper many to many relationship
$repo = $this->getDoctrine()->getRepository('YourBundle:Business');
$repo = $this->createQueryBuilder('b')
->addSelect('COUNT(DISTINCT c.id) AS total_categories')
->innerJoin('b.categories', 'c');
$categoryIds = array(1,2);
$repo->add('where', $qb->expr()->in('c', $categoryIds))
->groupBy('b.id')
->having('total_categories = '.count($categoryIds))
->getQuery()
->getResult();
For reference see another answer here
you can try
$qb->select( 'p' )
->from( 'AppBundle:Project', 'p' )
->innerJoin( 'p.users', 'u' )
->where( 'u.id=:userIdDaily' )
->andWhere('u.id=:UserID')
->setParameter( 'userIdDaily', $UserObj )
->setParameter( 'UserID', $UserObj->getId() )
;
$query = $qb->getQuery();
$results = $query->getResult();
i have project and user many to many relation. i use this to fetch data with multiple where clauses
I have an entity Log (table log) with members resourceType and resourceId (with columns resource_log and resource_id). The resourceType can e.g. Order (for actions on orders, e.g. status changes ) or Whatever (for Whatever related actions). There is no relationships (neither in Doctrine, nor in the database) between the Log and the "resource" entities/tables.
Now I want to select only the Logs, that are related to Orders with myOrderProperty = "someValue". That means:
SELECT
*
FROM
`log`
JOIN
`order` ON `order`.`id` = `log`.`resource_id` AND `log`.`resource_type` = 'order'
WHERE
`order`.`my_order_property` LIKE '%my_order_property_value%'
But the code
$queryBuilder = $this->entityManager->createQueryBuilder();
$queryBuilder->select('l')->from(Log::class, 'l');
$queryBuilder->join('l.order', 'o');
...
$queryBuilder
->where('o.myOrderProperty = :myOrderProperty')
->setParameter('myOrderProperty', $myOrderProperty);
doesn't work, since the entity Log doesn't have any relationship with the Order (though it has a property order):
[Semantical Error] line 0, col 102 near 'o WHERE o.myOrderProperty': Error: Class MyNamespace\Log has no association named order
How to JOIN without a relationship defined between two entities?
I know, I could use inheritance. But semantically it's not an inheritance case. So is there another way for solving the problem?
The JOIN without relationship can be implemented like this:
$queryBuilder = $this->entityManager->createQueryBuilder();
$queryBuilder->select('l')->from(Log::class, 'l');
$queryBuilder->join(
Order::class,
'o',
\Doctrine\ORM\Query\Expr\Join::WITH,
'o.id = l.resourceId'
);
...
$queryBuilder
->where('o.myOrderProperty = :myOrderProperty')
->setParameter('myOrderProperty', $myOrderProperty);
The only problem is, that the joined entities are not added to the main entity, so that $myLog->getOrder(...) returns null.
I have the following DQL:
$qb = $this->createQueryBuilder('p')
->select('PARTIAL p.{id, name}', 'p.sku', 'p.name', 'bu.abbreviation AS baseUnit', 'p.price',
'p.WP', 'p.SP', 'p.MP', 'p.PP', 'p.P3', 's.name as supplier')
->join('p.baseUnit', 'bu')
->join('p.suppliers', 's')
->where('p.active = 1');
Product has many suppliers and supplier can be in many products.
The problem in the query is that it returns only 1 supplier.
I tried searching the internet but it always has setParameter on it which i dont need since i just want to get all the products with their related suppliers only without any parameters or whatsoever.
How can I do that in DQL?
Thanks.
I've been trying with no success to user doctrine2 query builder to fetch records in a related many-to-many table using a where clause.
I would like to reproduce the following statement:
SELECT [...] FROM Company
JOIN CompanyAddress ON CompanyAddress.CompanyId = Company.Id
JOIN Address ON Address.Id = CompanyAddress.AddressId
WHERE Address.State = ?
following some ideias found on google, stackoverfow and doctrine docs:
$qb = $this->_em->createQueryBuilder();
$qb->select('c')
->from('Company', 'c')
->where(':State MEMBER OF c.Address')
->setParameter('State', $arguments);
but the results are not the desired one. Any help? Thanks..