如何在连接表上进行操作?

时间:2018-06-14 22:18:39

标签: sql symfony doctrine-orm

我有这个查询

$queryBuilder = $this->createQueryBuilder('u');

$queryBuilder->select('u')
    ->join('AppBundle\Entity\Company', 'c');
    ->where('c.owners = :u.id', 'LOWER(c.name) LIKE :searchInput')
    ->setParameter('searchInput', "%" . strtolower($searchInput) . "%");

此查询的目标是查找表Compagny,检查此表是否在其上拥有user_id,如果有,则搜索表Company的字段名称并将其与searchInput进行比较

不幸的是我有这个错误:

[Syntax Error] line 0, col 242: Error: Expected end of string, got '.'

知道为什么会这样吗?

class Company implements CompanyModelInterface
{
    //Other properties there

    /**
     * @var UserInterface[]
     */
    protected $owners;
}

我的.yml

manyToMany:
    owners:
      targetEntity: User
      joinTable:
        name: company_owners
        schema: public
        joinColumns:
          company_id:
            referencedColumnName: id
        inverseJoinColumns:
          user_id:
            referencedColumnName: id
            unique: true

1 个答案:

答案 0 :(得分:2)

如果您可以在其实体中指定用户和公司的映射,例如以教义方式进行映射,并且在连接部分中仅引用映射到另一个实体的那些属性,那就更好了

喜欢

class User
{

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Company", inversedBy="owners")
     * @ORM\JoinColumn(nullable=false)
     */
    private $company;
}

class Company
{
    // ...

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\User", mappedBy="company")
     */
    private $owners;
}

使用查询构建器,您可以写为

$queryBuilder = $this->createQueryBuilder('u');
$queryBuilder->select('u')
    ->join('u.company', 'c');
    ->where('c.name LIKE :searchInput')
    ->setParameter('searchInput', "%" . strtolower($searchInput) . "%");

目前,如果您尚未定义任何映射但仍想加入2个实体,则可以使用WITH子句

$queryBuilder = $this->createQueryBuilder('u');

$queryBuilder->select('u')
    ->join('AppBundle\Entity\Company', 'c', 'WITH', 'c.owners = u.id');
    ->where('c.name LIKE :searchInput')
    ->setParameter('searchInput', "%" . strtolower($searchInput) . "%");

Mapping the ManyToOne Relationship

如果您在后端使用Mysql数据库,我建议您将表格排序设置为不区分大小写,这样您就不需要使用LOWER/UPPER函数

B.5.4.1 Case Sensitivity in String Searches

将映射定义为双向,如用户定义为

User:
  type: entity
  manyToMany:
    companies:
      targetEntity: Company
      mappedBy: owners

对于公司

manyToMany:
    owners:
      targetEntity: User
      inversedBy: companies
      joinTable:
        name: company_owners
        schema: public
        joinColumns:
          company_id:
            referencedColumnName: id
        inverseJoinColumns:
          user_id:
            referencedColumnName: id
            unique: true

然后你可以写为

$queryBuilder = $this->createQueryBuilder('u');
$queryBuilder->select('u')
    ->join('u.companies', 'c');
    ->where('c.name LIKE :searchInput')
    ->setParameter('searchInput', "%" . strtolower($searchInput) . "%");