Symfony 2.7 - 找不到列 - 多对多关系

Symfony 2.7 - Column not found - many to many relation

问题:我试图通过向我的查询提供用户 ID 来获取与用户相关的所有公司。

我遇到的错误:

CRITICAL - Uncaught PHP Exception Doctrine\DBAL\Exception
\InvalidFieldNameException: "An exception occurred while executing 'SELECT
t0.id AS id_1, t0.name AS name_2, t0.phone AS phone_3, t0.fax AS fax_4, 
t0.country AS country_5, t0.address AS address_6, t0.zipcode AS zipcode_7, 
t0.state AS state_8, t0.city AS city_9, t0.notes AS notes_10 FROM company t0
 WHERE company_representatives.user_id = ?' with params [177]: 
SQLSTATE[42S22]: Column not found: 1054 Unknown column 
'company_representatives.user_id' in 'where clause'" at C:\wamp64
\www\Portail\vendor\doctrine\dbal\lib\Doctrine\DBAL\Driver
\AbstractMySQLDriver.php line 71 

我有一个实体 "Company",它与我的实体 "User"

存在多对多关系

Company.php

 /**
 * @var ArrayCollection
 *
 * @ORM\ManyToMany(targetEntity="Dbm\UserBundle\Entity\User")
 * @ORM\JoinTable(name="company_representatives")
 */
private $representatives;

User.php 与其实体 class 中的公司没有任何关系。

由于我的 ManyToMany 关系,我确实有一个 company_representatives table 其中包含“company_id”和“user_id

下面的代码是导致 "Column not found" 错误的原因。

$companies = $em->getRepository('DbmPortalBundle:Company')->findBy(array('representatives' => $user->getId()));

-缓存已清除

-[映射] 和 [数据库] = 使用 doctrine:schema:validate

时正常

-我在构造函数中将代表实例化为 ArrayCollection

编辑

我使用了一种暂时可以解决问题的解决方法。我显然想稍后解决这个问题。我的解决方法是直接在我的 "company_representatives" table 上使用原始 SQL 来查找链接到我的 user_id 的所有公司的 ID。这样我就可以使用 "FindBy" 和他们在我公司存储库中的 ID 来获取所有公司的对象。

您是否在 Company.php 的 _construct() 方法中初始化 ArrayCollection?

// Entity/Company.php

public function __construct() {
    $this->representatives = new \Doctrine\Common\Collections\ArrayCollection();
}

...

请参阅学说文档 here

尝试php app/console doctrine:schema:update --force

您不能将 findBy(或任何查找方法)用于 多对多 关系(也许将来会支持). 您的条件构造正确“WHERE company_representatives.user_id = ?' with params [177]" by doctrine 但没有添加与 company_representatives 的连接。

你想要的是获得一个用户的所有公司,我建议也将关系添加到用户实体:

/**
 * @var ArrayCollection
 *
 * @ORM\ManyToMany(targetEntity="Company", inversedBy="representatives")
 * @ORM\JoinTable(name="company_representatives")
 */
private $companies;

public function __construct()
{
    $this->companies = new ArrayCollection();
}

public function getCompanies()
{
    return $this->companies;
}

终于可以直接从用户实体获取公司了:

$user->getCompanies();