【问题标题】:Simplify Doctrine code in Controller简化 Controller 中的 Doctrine 代码
【发布时间】:2012-05-11 17:21:06
【问题描述】:

(对不起我的英语不好)

我是 Symfony2/Doctrine 的新手,目前正在做我的第一个项目。有没有办法简化下面的代码?

我有两个实体,一个包含订单,另一个实体包含订单状态(新、进行中、已发送……)。订单有一个“状态”字段,它与状态实体中的“状态”id 字段是一对多的。

当我创建一个新订单时,我必须为订单分配一个状态,使用以下代码:

$order = new Order();
$order->setStatus($this->getDoctrine()->getEntityManager()->getRepository('OrderBundle:Status')->findOneByStatus(0));

“0”表示状态“新”。我认为可以简化此代码,但找不到如何执行此操作。

有什么想法吗?

谢谢!

【问题讨论】:

    标签: symfony doctrine


    【解决方案1】:

    您需要引入实体之间的关系(例如,多对一)。检查official Doctrine documentation

    另一种选择,如果你不想用关系来限制你的实体,你可以把逻辑放到custom entity repositories。这会稍微减少代码量。

    【讨论】:

    • 但是,关系已经完成。这只是因为我必须使用: $order->setStatus($this->getDoctrine()->getEntityManager()->getRepository('OrderBundle:Status')->findOneByStatus(0));而不是 $order->setStatus(0);我想简化该代码,或者这可能是唯一的方法。
    • 我将定义管理器服务(定义为prototype 并接受 entityManager 的参数)并创建一个类似setStatusById() 的方法,在该方法中像现在一样使用 entityManager 来查找并将其设置为Order 的一个属性,以便您的代码将转换为:$order = $this->get('order_manager'); $order->setStatusById(0); 希望它有所帮助。如果没有 - 询问更多:)
    猜你喜欢
    • 2016-09-24
    • 1970-01-01
    • 1970-01-01
    • 2011-08-09
    • 1970-01-01
    • 2015-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多