【问题标题】:DQL - fetching related entitiesDQL - 获取相关实体
【发布时间】:2011-05-04 23:21:08
【问题描述】:

通常我只会延迟加载我的实体,但现在我需要创建一个能够将节点作为数组获取的 DQL。我已经尝试了几个查询,但我无法让它工作,下面是两个例子:

// example one
$this->em->createQuery('SELECT n FROM Entities\Node n WHERE n.nodeType INSTANCE OF ?1')
    ->setParameter(1, $type)->getArrayResult();
// example two
$this->em->createQuery('SELECT n FROM Entities\Node n WHERE n.nodeType_id = ?1')
    ->setParameter(1, $type->id)->getArrayResult();

我不确定 INSTANCE OF 实际做了什么,但它不起作用,使用 nodeType_id 也不起作用,因为我的注释没有 nodeType_id 只有数据库表有。

那么什么是正确的方法呢?

【问题讨论】:

    标签: php orm doctrine-orm dql


    【解决方案1】:

    什么是节点类型?如果它只是一个字符串,那么你只需要:

    $this->em
        ->createQuery('SELECT n FROM Entities\Node n WHERE n.nodeType = ?1')
        ->setParameter(1, $type)
        ->getArrayResult();
    

    如果您使用继承并且想要特定类型的节点,请使用:

    $this->em
        ->createQuery("SELECT n FROM Entities\Node n WHERE n INSTANCE OF $type")
        ->getArrayResult();
    

    注意 $type 应该类似于:$type = 'Entities\Nodes\NodeSubclass'。不能作为参数添加。

    【讨论】:

    • NodeType 是另一个实体,我在 node 和 nodeType 之间有一个多对一关系
    【解决方案2】:

    我只需要像这样使用等号:

    $this->em->createQuery('SELECT n FROM Entities\Node n WHERE n.nodeType = ?1')
        ->setParameter(1, $type->id)->getArrayResult();
    

    其中 type 是另一个实体。

    【讨论】:

    • 如果您的答案有效 - 太好了!如果您需要 nodeType 上的其他条件,那么更一般的情况是使用连接:'SELECT n FROM Entities\Node n JOIN n.nodeType nt WHERE nt.id = ?1' and nt.someOtherProperty = ?2'
    猜你喜欢
    • 2012-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多