How to JOIN without a relationship in Doctrine?

我与影子孤独终老i 提交于 2019-12-22 08:12:57

问题


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?


回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!