[英]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
我有一个实体“公司”,它与我的实体“用户”具有ManyToMany关系
Company.php
/**
* @var ArrayCollection
*
* @ORM\ManyToMany(targetEntity="Dbm\UserBundle\Entity\User")
* @ORM\JoinTable(name="company_representatives")
*/
private $representatives;
User.php在其实体类中与Company没有关系。
由于我与ManyToMany的关系,我确实有一个company_representatives表,其中包含“ company_id ”和“ user_id ”
下面的代码是导致“找不到列”错误的原因。
$companies = $em->getRepository('DbmPortalBundle:Company')->findBy(array('representatives' => $user->getId()));
-缓存已清除
-当使用doctrine:schema:validate时,[[Mapping]和[Database] = OK
-我在构造函数中将代表实例化为ArrayCollection
编辑
我使用了一种解决方法,现在可以解决问题。 我显然会在以后解决此问题。 我的解决方法是直接在“ company_representatives”表上使用原始SQL,以查找链接到我的user_id的所有公司的ID。 这样,我就可以在公司存储库中使用带有其ID的“ FindBy”来获取所有公司的对象。
您要在Company.php的_construct()方法中初始化ArrayCollection吗?
// Entity/Company.php
public function __construct() {
$this->representatives = new \Doctrine\Common\Collections\ArrayCollection();
}
...
请参阅此处的学说文档。
尝试使用PHP应用程序/控制台学说:schema:update --force
您不能使用具有多对多关系的findBy (或任何find方法)(也许将来会支持)。 您的条件是正确构造的“ WHERE company_representatives.user_id =?” 带有参数的[177]参数 ,但不添加与company_representatives的连接。
您想要得到的是一个用户的所有公司,我建议也将关系添加到User实体:
/**
* @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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.