使用Criteria过滤的“IN”谓词不起作用

时间:2016-02-12 09:07:36

标签: doctrine-orm doctrine

我正在尝试使用Criteria直接过滤学说集合,以避免在我只搜索某些元素时进行所有集合加载。

public function bar()
{
    $entity = ...; // not useful for the example
    $property = ...; // not useful for the example but is a getter for a collection
    $ids = [22, 13]; // just for the sake of this example
    $criteria = Criteria::create()->where(Criteria::expr()->in("id", $ids));

    return $this->foo($entity, $property, $criteria);
}

public function foo($entity, $property, Criteria $criteria)
{
    return $this->propertyAccessor->getValue($entity, $property)->matching($criteria);
}

上面的代码将产生这个DQL(我只显示最后和相关部分)

  

AND te.id =?'与params [22,13]:

所以,这个错误

  

注意:数组转换为字符串

我认为这里生成了错误的DQL,但我不知道为什么。

有没有人知道?

这是我想要匹配的集合属性

/**
 * @ORM\ManyToMany(targetEntity="Vendor\Bundle\Entity\Foo")
 * @ORM\JoinTable(name="foo_bar",
 *     joinColumns={@ORM\JoinColumn(name="foo_bar_id", referencedColumnName="id", onDelete="cascade")},
 *     inverseJoinColumns={@ORM\JoinColumn(name="foo_id", referencedColumnName="id")}
 * )
 */
 protected $foo;

修改

如果我尝试转储$criteria对象,我会获得此

Criteria {#10958 ▼
  -expression: Comparison {#10956 ▼
    -field: "id"
    -op: "IN"
    -value: Value {#10948 ▼
      -value: array:2 [▼
        0 => 22
        1 => 13
      ]
    }
  }
  -orderings: []
  -firstResult: null
  -maxResults: null
}

所以这似乎是正确的。我也知道我可以使用“或”表达式,但我更愿意理解为什么会出现这个问题。

EDIT2

我已按以下方式更改$criteria

$criteria = Criteria::create()
    ->where(Criteria::expr()->eq('id', 22))
    ->orWhere(Criteria::expr()->eq('id', 13));

现在,查询是正确的但是集合不是:它是空的但不应该是(如果我从mysql cli手动运行该查询,我得到了我期望的结果)。

所以......

奖金问题

如果我的集合尚未加载,我可以仅在实体getter或存储库中使用Criteria吗?

编辑3 - 奖金问题

似乎如果你没有已经加载的集合,匹配标准就没用了。事实上,如果我循环到集合元素并调用一些getter,然后,我使用条件,结果集合是我正在搜索的(但是,当然,现在加载了所有集合元素)

1 个答案:

答案 0 :(得分:1)

我发现了这个

https://github.com/doctrine/doctrine2/issues/4910

这似乎是一个众所周知的" ManyToMany收集情况中的问题

相关问题