问题
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 Log
s, that are related to Order
s 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?
回答1:
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
.
来源:https://stackoverflow.com/questions/45900627/how-to-join-without-a-relationship-in-doctrine