【问题标题】:Symfony 2.7 - Column not found - many to many relationSymfony 2.7 - 未找到列 - 多对多关系
【发布时间】:2017-11-24 19:48:13
【问题描述】:

问题:我试图通过向我的查询提供用户 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 

我有一个实体“公司”,它与我的实体“用户”具有多对多关系

公司.php

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

User.php 在他的实体类中与 Company 没有关系。

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

下面的代码是导致“找不到列”错误的原因。

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

-缓存已被清除

-[映射] 和 [数据库] = 使用教义时正常:模式:验证

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

编辑

我使用了一种解决方法,现在可以解决问题。我显然想稍后解决这个问题。我的解决方法是直接在我的“company_representatives”表上使用原始 SQL 来查找链接到我的 user_id 的所有公司的 id。然后,我可以在我的公司存储库中使用带有他们 ID 的“FindBy”来获取所有公司的对象。

【问题讨论】:

    标签: php symfony doctrine entitymanager symfony-2.7


    【解决方案1】:

    您不能将 findBy(或任何 find 方法)与 Many to Many 关系一起使用(也许将来会支持)。 您的条件构造正确“WHERE company_representatives.user_id = ?'带有参数 [177]”,但没有添加与 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();
    

    【讨论】:

      【解决方案2】:

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

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

      请参阅教义文档here

      【讨论】:

      • 它没有用。我也尝试将我的实体设置为 ManyToMany Bidirectional,但在缓存清除后我仍然遇到同样的错误
      【解决方案3】:

      尝试 php app/console 学说:schema:update --force

      【讨论】:

        猜你喜欢
        • 2015-05-25
        • 1970-01-01
        • 2021-09-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-11-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多