gpt4 book ai didi

mysql - Doctrine 多对多连接表未填充

转载 作者:行者123 更新时间:2023-11-29 21:56:51 26 4
gpt4 key购买 nike

我有以下学说.ORM.XML文件。我已经更新了架构,可以查看数据库中的所有表和连接表,并且可以很好地实例化 ProductOrder 的实体。

Products.orm.xml:

<entity name="Product" table="product"
repository-class="AppBundle\Entity\ProductRepository">

<many-to-many target-entity="Order" inversed-by="Product" field="orders">
<join-table name="products_orders">
<join-columns>
<join-column name="Product_id" referenced-column-name="id"/>
</join-columns>
<inverse-join-columns>
<join-column name="Orders_id" referenced-column-name="id"/>
</inverse-join-columns>
</join-table>
</many-to-many>
</entity>

Orders.orm.xml:

<entity name="Order" table="order"
repository-class="AppBundle\Entity\OrderRepository">

<many-to-many field="products" mapped-by="orders" target-entity="Product" />
</entity>

但是,当我 flush() 一个实体到数据库时,它仅在 Product/Order 表中单独创建,而没有正如我所期望的,相应的关键记录正在 products_orders 连接表中生成。下面是我在 Controller 中 flush() 到数据库的代码 - 我是否需要以某种方式对此进行扩展以处理 products_orders 连接表?

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;
use FOS\RestBundle\Controller\FOSRestController;
use AppBundle\Entity\Product;
use AppBundle\Entity\Order;

class DefaultController extends FOSRestController
{
/**
* @Route("/neworder", name="new_order")
*/
public function newOrderAction(Request $request)
{
$order = new Order();
$em = $this->getDoctrine()->getManager();

$products = $em->getRepository('AppBundle:Product')
->findAllOrderedByName();

$form = $this->CreateFormBuilder($order)
->add('products', 'entity', array(
'class' => 'AppBundle:Product',
'choice_label' => 'Description',
))
->add('Quantity', 'integer')
->add('Units', 'text')
->add('Save', 'submit', array('label' => 'Create Order'))
->getForm();


$form->handleRequest($request);
if ($form->isValid()) {
$em->persist($order);
$em->flush();
return $this->redirectToRoute('homepage');
}

return $this->render('AppBundle:Default:new.order.form.html.twig', array(
'form' => $form->createView(),
));

}
}

编辑:

根据 Cerad 的建议,我在下面添加了 Order 实体定义的代码,其中添加了 addProduct() 函数。我还向我的 Product 实体代码添加了相应的 addOrder() 方法:

namespace AppBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;

class Order
{
protected $id;
public $products;
public function __construct()
{
$this->products = new ArrayCollection();
}


public function addProduct($product) {
$product->addOrder($order);
}
#....
}

但是,当我尝试更新学说实体时,我收到错误:

Compile Error: Cannot redeclare AppBundle\Entity\Order::addProduct

最佳答案

我猜您的 Order::addProduct 看起来像这样:

class Order {
addProduct($product) {
$this->products[] = $product;

如果是这样,那么您没有告诉产品有关新订单的信息。您需要添加

    $product->addOrder($order);

这将完成您的双向引用,并且应该允许持久按预期工作。如果您已经有了上面的代码,那么还有其他问题。

关于mysql - Doctrine 多对多连接表未填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33068365/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com