【问题标题】:Can I search an entity's child properties in Symfony/ORM?我可以在 Symfony/ORM 中搜索实体的子属性吗?
【发布时间】:2015-11-21 03:22:11
【问题描述】:

我正在为我的公司实体创建一个搜索功能,并使用 Symfony 2 和 Doctrine ORM 将我的逻辑放入自定义实体存储库中。

公司实体有一个子集合 Locations,因为公司可以有多个位置,以及一个公司名称字段。

我想知道是否可以使用查询生成器按公司名称和 Location[1].address、Location[2].address 等进行搜索。

这是我到目前为止所拥有的,找不到学习这个的好资源。

*/ AppBundle/Repository/CompanyRepository.php */

class CompanyRepository extends EntityRepository
{

    public function findBySearch($options)
    {
        $query = $this->createQueryBuilder('c');

        foreach ($options as $key => $value) {
            $query->where('c.' . $key . ' LIKE :' . $key);
            $query->setParameter($key, '%' . $value . '%');
        }

        return $query->getQuery()->getResult();
    }
}

看起来这不起作用:

 $query->where('c.locations.city LIKE $city);

findBySearch() 中的 $options 参数示例如下:

[ 
    'companyName' => 'Mikes Company',
    'locations.city' => 'New York',
    'locations.state' => 'New York'
]

非常感谢任何建议或资源链接。

【问题讨论】:

    标签: symfony search doctrine-orm


    【解决方案1】:

    您选择了c,之后您要查找具有某个位置的公司,这意味着在公司实体中您应该有(类型为Location)字段location。位置实体应该有字段(字符串)城市。公司实体中的字段位置应具有 oneToMany association 和 LocationEntity。之后,当您添加公司名称时,您还将添加公司的位置。现在你可以写了:

    $query->leftJoin('c.locations', 'locations');
    $query->where('locations.city LIKE :city');
    $query->setParameter('city', '%'.$city.'%')
    

    如果你想使用位置对象的c.locations.city 属性,你应该调用那里的关联。喜欢leftJoin, innerJoin。但我认为innerJoin这里会更好,只需两行。

    $query->innerJoin('c.locations', 'locations', 'WITH', 'locations.city LIKE (:city)')
    $query->setParameter('city', '%'.$city.'%')
    

    【讨论】:

      【解决方案2】:

      尝试将$query->where 更改为$query->andWhere

      ->andWhere()可以直接使用,前面没有->where()

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多