【问题标题】:ManyToOne / OneToMany with custom join column带有自定义连接列的 ManyToOne / OneToMany
【发布时间】:2016-02-12 17:40:33
【问题描述】:

我正在使用现有的数据库,其中的字段关联性不太好。我已经能够让其他 ManyToOne 和反之亦然的关系正常工作(我在项目中创建数据库的地方),但是这个预先存在的数据库让我陷入了循环。

我有一个名为 franchisee_creds,ManyToOne 的表,其中有一个字段 franchisee_id,需要映射到另一个名为 accounts 的表,OneToMany,还有一个名为 franchisee_number 的字段,一个字符串。

FranchiseeCreds.php:

 /**
 * @ORM\ManyToOne(
 *     targetEntity="Inertia\InertiaBundle\Entity\Accounts",
 *     inversedBy="franchiseeCreds",
 *     fetch="EAGER"
 * )
 * @ORM\JoinColumn(name="franchisee_id", referencedColumnName="franchisee_number")
 */
private $accounts;

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

...

 /**
 * @return ArrayCollection
 */
public function getAccounts()
{
    return $this->accounts;
}

Accounts.php

 /**
 * @ORM\OneToMany(targetEntity="Inertia\InertiaBundle\Entity\FranchiseeCreds", mappedBy="accounts")
 */
private $franchiseeCreds;

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

...

/**
 * @return mixed
 */
public function getFranchiseeCreds()
{
    return $this->franchiseeCreds;
}

控制器:

  public function showAction($id)
{
    $em = $this->getDoctrine()->getManager('inertia');

    $entity = $em->getRepository('InertiaBundle:Accounts')->find($id);

    if (!$entity) {
        throw $this->createNotFoundException('Unable to find Accounts entity.');
    }

    $deleteForm = $this->createDeleteForm($id);

    return $this->render('InertiaBundle:Accounts:show.html.twig', array(
        'entity'      => $entity,
        'delete_form' => $deleteForm->createView(),
    ));
}

然后在我看来,如果我将 {{ dump(entities) }} 放在 Accounts 和 FranchiseeCreds show.html.twig 上,关系就会出现,但始终是 null

【问题讨论】:

  • 你在控制器上做什么以及你传递给 Twig 视图的内容是什么?
  • 我添加了控制器。树枝视图只是自动生成的视图,我只是添加了 {{ dump(entity) }} ,这样我就可以看到我得到了什么数据。
  • 根据您的控制器,{{ dump(entities) }} 什么都不做...因为您没有将任何 entities 变量传递给您的控制器

标签: symfony doctrine one-to-many many-to-one


【解决方案1】:

我遇到的最大问题是当我运行时,当数据在表中时,学说无法将外键添加到表中:

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

我做了一个备份,截断了有问题的表,重新运行了doctrine:schema:update 命令,恢复了数据,一切正常。

我还误以为当我将{{ dump(entity) }} 放入我的代码中时,我能够看到一系列相关项目。我误解了。当我真正去工作运行for循环并打印出数据时,它工作正常,在我修复了数据库之后。

【讨论】:

  • 你用问题截断了他们? ;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-14
  • 1970-01-01
  • 1970-01-01
  • 2012-12-01
  • 2023-03-27
相关资源
最近更新 更多