背景
我的数据库中有两个表,CampaignList和CampaignProduct。逻辑很简单,如果用户成功购买产品,我必须根据购买的产品数量创建一个新的CampaignList和CampaignProducts。这两个表将在未来一起映射,现在我只是想正确插入它们。
因此,例如,如果用户成功购买了3个产品,则在CampaignList中插入一个新表,并且3个新表是CampaignProduct。
现在产品在会话中存储如下:
11 => 2
29 => 1
key
是产品的ID,value
是数量。所以本次会议有3个产品,两个id为11的产品和一个id为29的产品。现在问题和代码。
问题
插件工作正常,除了一个。我需要在数据库中保存产品的数量。但这种方式我正在创造我不认为我可以吗?因为我在不同的循环中创建表,其中数量从不迭代?这是代码
代码
if ($session->has('cart') && count($session->get('cart')) > 0) {
// if the session is good create the new campaign
$campaign = New CampaignList();
$campaign->setUserId($user->getId());
$campaign->setName('Karpedeal');
$campaign->setState(1);
$em->persist($campaign);
$em->flush();
foreach ($cart as $id => $quantity) {
// store the product ids in an array
$productIds[] = $id;
//get all the products based on the id array
$product = $em->getRepository('MpShopBundle:Product')->findById($productIds);
}
// for each new product create new CampaignProduct
foreach($product as $item){
$campaignProduct = New CampaignProduct();
$campaignProduct->setCampaignId($campaign->getId());
$campaignProduct->setProductId($item->getId());
$campaignProduct->setSellingPrice($item->getPrice());
$campaignProduct->setStock($item->getStockAvailable());
$campaignProduct->setReserved($quantity); // PROBLEM how to get the quantity from the session??
$em->persist($campaignProduct);
$em->flush();
}
其他方式
我认为我能做的唯一方法是在第一个foreach循环中执行所有操作,但是当我尝试获取产品的ID时,我会收到错误,因为它们不是对象,而是数组......
if ($session->has('cart') && count($session->get('cart')) > 0) {
// if the session is good create the new campaign
$campaign = New CampaignList();
$campaign->setUserId($user->getId());
$campaign->setName('Karpedeal');
$campaign->setState(1);
$em->persist($campaign);
$em->flush();
foreach ($cart as $id => $quantity) {
// store the product ids in an array
$productIds[] = $id;
//get all the products based on the id array
$product = $em->getRepository('MpShopBundle:Product')->findById($productIds);
$campaignProduct = New CampaignProduct();
$campaignProduct->setCampaignId($campaign->getId());
$campaignProduct->setProductId($product->getId()); // the error here because $product is an array not object
$campaignProduct->setSellingPrice($item->getPrice());
$campaignProduct->setStock($product->getStockAvailable());
$campaignProduct->setReserved($quantity); // PROBLEM how to get the quantity from the session??
$em->persist($campaignProduct);
$em->flush();
}
有什么想法吗?
答案 0 :(得分:3)
通过查看您的代码,我猜您的第二个答案是最好的,但不是让所有产品都包含一系列产品ID,而是每次运行都会获得一个产品,从而使您的产品成为MpShopBundle:Product
的实例
TL;博士
改变这一点
$product = $em->getRepository('MpShopBundle:Product')->findById($productIds);
$product = $em->getRepository('MpShopBundle:Product')->find($id);
应该工作