【问题标题】:How to handle Doctrine relationships with Twig如何处理与 Twig 的教义关系
【发布时间】:2017-06-18 00:20:36
【问题描述】:

我有两个实体,Customers 和 Locations。他们处于ManyToOne 关系中(一个客户可以有多个位置)。

这就是我定义关系的方式:

    class Customers { 
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=45)
     */
    private $name; 
    }

还有实体Locations:

class Locations { 
/**
 * @ORM\Column(type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @ORM\ManyToOne(targetEntity="Customers", inversedBy="id")
 * @ORM\JoinColumn(name="customers_id", referencedColumnName="id")
 */
private $customers_id;

/**
 * @ORM\Column(type="string", length=90)
 */
private $name;
}

我希望能够单击用户并在 Twig 模板中呈现与他关联的所有位置。这就是我现在这样做的方式,但我不确定这是正确的方式。 首先是控制器:

/**
* @Route("/showLocations/{id}", name = "show_locations")
* @Method("GET")
**/
public function showLocationsAction($id) {

    $repository = $this->getDoctrine()->getRepository('AppBundle:Locations');
    $locations = $repository->findBy(array('customer_id' => $id ));
    $repository = $this->getDoctrine()->getRepository('AppBundle:Customers');
    $customer = $repository->findOneById($id);

    if(!empty($locations)) {
    return $this->render("AppBundle:Default:showLocations.html.twig", array('locations' => $locations, 'customer' => $customer)); }

    else return new Response ("There are no locations to show");
}

这是树枝模板:

<p>Locations associated with {{customer.name}}</p>
<table id="table_id" class="display">
<thead>
    <tr>
        <th>Locations</th>
    </tr>
</thead>
<tbody>
    {% for locations in locations %}
    <tr>
        <td>{{ locations.name|e }}</td>
    </tr>
    {% endfor %}
</tbody>

有什么建议吗?谢谢!

【问题讨论】:

  • 目前看起来还不错。但是命名 $customers_id 应该只是 $customer。
  • 通常你会有一个 Customer::locations 属性,它与 Location 是一对多的关系。这样,加载客户将无需任何进一步的努力即可提供位置。看一下产品/类别示例:symfony.com/doc/current/doctrine/… 在您的情况下,客户是类别,位置是产品。并为自己节省一些未来的混乱,将您的实体命名为客户而不是客户和位置而不是位置。

标签: symfony orm doctrine twig


【解决方案1】:

目前看起来还不错。但是 $customers_id 的命名应该只是 $customer,因为 Doctrine 会自动获取相关的客户并将其合并为一个对象。

然后您可以使用{{ location.customer.name }} 获取并显示客户

$repository = $this->getDoctrine()->getRepository('AtlasBundle:Customers'); $customer = $repository->findOneById($id);

那么可以完全省略。

【讨论】:

  • 抱歉,您的意思是将 Locations 私有属性 $customer_id 称为 $customer?
  • 内部 Twig 将在 Locations 类上查找名为 ::getCustomer() 的公共方法并首先使用它:twig.sensiolabs.org/doc/2.x/templates.html(参见“实现”部分)
  • 好的,除了{{ location.customer.name }} 部分外,它可以工作。我收到此错误Key "customers" for array with keys "0, 1" does not exist. 在模板中,如果我 dump Locations,我可以看到 Customers 的名称设置为 null。
  • 我可以用{{ location.0.customer.name }} 打印客户名称。对吗?
  • @Dygne:这看起来您的映射无效。每个位置似乎有 2 个客户?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-04-08
  • 1970-01-01
  • 2012-08-03
  • 2021-10-07
  • 2018-08-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多