当前位置: 首页 > 知识库问答 >
问题:

Symfony 3异常:类型错误:参数1传递给原则\common\collections\ArrayCollection

俞涵涤
2023-03-14

请帮我做一个购物车的项目。我试图将产品添加到basket,但在添加新产品时得到了这个错误:Type error:传递给decility\common\collections\arraycollection::__construct()的参数1必须是array类型,对象给定,在C:\users\Angel's\desktop\untitled2\vendor\decility\orm\lib\decility\orm\unitofwork.php第605行中调用。

以下是我的CartController:

<?php

namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use AppBundle\Entity\Product;
use AppBundle\Entity\Cart;
use AppBundle\Entity\Shipping;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
class CartController extends Controller
{
    /**
     * @Route("/", name="homepage")
     */
    /*public function indexAction(Request $request)
    {
        // replace this example code with whatever you need
        return $this->render('default/index.html.twig', array(
            'base_dir' => realpath($this->container->getParameter('kernel.root_dir').'/..').DIRECTORY_SEPARATOR,
        ));
    }*/
    /**
     * @Route("/cart", name="view_cart")
     */
    public function showAction()
    {
        # Get object from doctrine manager
        $em = $this->getDoctrine()->getManager();
        # Get logged user then get his ['id']
        $user = $this->container->get('security.token_storage')->getToken()->getUser();
        /** Check IF user have exist cart  **/
        # select cart from database where user id equal to cureent logged user using [ findByUser() ]
        $user_cart = $this->getDoctrine()
            ->getRepository('AppBundle:Cart')
            ->findBy(['user' => $user]);
        if ( $user_cart )
        {
            # Then select all user cart products to display it to user
            $user_products = $this->getDoctrine()
                ->getRepository('AppBundle:Shipping')
                ->findBy( array('cart' => $user_cart[0]->getId()) );
            # pass selected products to the twig page to show them
            return $this->render('cart/show.html.twig', array(
                'products'  => $user_products,
                'cart_data' => $user_cart[0],
            ));
        }
        //return new Response(''. $user_products[0]->getProduct()->getPrice() );
        # pass selected products to the twig page to show them
        return $this->render('cart/show.html.twig');
    }

    /**
     * @Route("/cart/addTo/{productId}", name="add_to_cart")
     * @param $productId
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function addAction($productId)
    {
        # First of all check if user logged in or not by using FOSUSERBUNDLE
        #    authorization_checker
        # if user logged in so add the selected product to his cart and redirect user to products page
        # else redirect user to login page to login first or create a new account
        $securityContext = $this->container->get('security.authorization_checker');
        # If user logged in
        if ( $securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED') )
        {
            # Get object from doctrine manager
            $em = $this->getDoctrine()->getManager();
            # Get logged user then get his ['id']
            $user = $this->container->get('security.token_storage')->getToken()->getUser();
            # for any case wewill need to select product so select it first
            # select specific product which have passed id using ['find(passedID)']
            $product = $this->getDoctrine()
                ->getRepository('AppBundle:Product')
                ->find($productId);
            /** Check IF user have exist cart  **/
            # select cart from database where user id equal to cureent logged user using [ findByUser() ]
            $exsit_cart = $this->getDoctrine()
                ->getRepository('AppBundle:Cart')
                ->findBy(['user' => $user]);
            # if there's no cart to this user create a new one
            if ( !$exsit_cart )
            {
                # defince cart object
                $cart = new Cart();
                # set user whose own this cart
                $cart->setUser($user);

                # set initail total price for cart which equal to product price
                $cart->setTotalPrice($product->getPrice());
                $cart->setQuantity(1);
                # persist all cart data to can use it in create shipping object
                $em->persist($cart);
                # flush it
                $em->flush();
                # create shipping object
                $ship = new Shipping();
                # set all its data quantity initail equal to 1 and passed product and cart created
                $ship->setQuantity(1);
                $ship->setProduct($product);
                $ship->setCart($cart);
                # persist it and flush doctrine to save it
                $em->persist($ship);
                $em->flush();
            }
            # if user have one so just add new item price to cart price and add it to shipping
            else
            {
                # Get cart from retrived object
                $cart = $exsit_cart[0];

                # set initail total price for cart which equal to product price
                $cart->setTotalPrice($cart->getTotalPrice() + $product->getPrice());
                # persist all cart data to can use it in create shipping object
                $em->persist($cart);
                # flush it
                $em->flush();
                # create shipping object
                $ship = new Shipping();
                # set all its data quantity initail equal to 1 and passed product and cart created
                $ship->setQuantity(1);
                $ship->setProduct($product);
                $ship->setCart($cart);
                # persist it and flush doctrine to save it
                $em->persist($ship);
                $em->flush();
            }
            //return new Response('user id  '.$product->getId());
            return $this->redirect($this->generateUrl('products_index'));
        }
        # if user not logged in yet
        else
        {
            # go to adding product form
            return $this->redirect($this->generateUrl('login'));
        }
    }
    /**
     * @Route("/cart/remove/{itemProduct}/{itemCart}", name="remove_item")
     */
    public function removeActione($itemProduct, $itemCart)
    {
        # get an object from doctrine db and get Shipping Entity to work on it
        $em = $this->getDoctrine()->getManager();
        $repository = $em->getRepository('AppBundle:Shipping');
        # select wanted item from shipping table to delete it
        $ship = $repository->findOneBy(array('product' => $itemProduct, 'cart' => $itemCart));
        # Calculate the new total price for cart by subtract deleted item price from total one
        $final_price = $ship->getCart()->getTotalPrice() - ($ship->getProduct()->getPrice() * $ship->getQuantity());
        # update the total price of cart
        $ship->getCart()->setTotalPrice($final_price);
        # Remove item from db
        $em->remove($ship);
        $em->flush();
        return $this->redirect($this->generateUrl('view_cart'));
    }
    /**
     * @Route("/cart/edit/{itemProduct}/{itemCart}", name="edit item")
     */
    public function editActione(Request $request, $itemProduct, $itemCart)
    {
        # in the start check if user edit field and click on button
        if ( $request->getMethod() === 'POST' )
        {
            # read data from quantity field
            $new_quantity =$request->request->get('quantity');
            # get oject from doctrine manager to mange operation
            $em = $this->getDoctrine()->getManager();
            $repository = $em->getRepository('AppBundle:Shipping');
            # select wanted item from shipping table to edit it
            $ship = $repository->findOneBy(array('product' => $itemProduct, 'cart' => $itemCart));
            # check if new quantity less than old one so subtract total price
            # otherwise, add to it
            if( $ship->getQuantity() < $new_quantity )
            {
                # edit selected item quantity
                $ship->setQuantity($new_quantity);
                # Calculate the new total price for cart by sum added item price to total one
                $final_price = $ship->getCart()->getTotalPrice() + $ship->getProduct()->getPrice();
                # update the total price of cart
                $ship->getCart()->setTotalPrice($final_price);
            }
            elseif( $ship->getQuantity() > $new_quantity )
            {
                # edit selected item quantity
                $ship->setQuantity($new_quantity);
                # Calculate the new total price for cart by sum added item price to total one
                $final_price = $ship->getCart()->getTotalPrice() - $ship->getProduct()->getPrice();
                # update the total price of cart
                $ship->getCart()->setTotalPrice($final_price);
            }
            # flush operations to update database
            $em->flush();
        }
        //return new Response(''. $new_quantity );
        return $this->redirect($this->generateUrl('view_cart'));
    }
    /**
     * @Route("/cart/clear/{cart}", name="clear_cart")
     */
    public function clearActione($cart)
    {
        # get an object from doctrine db and get Shipping Entity to work on it
        $em = $this->getDoctrine()->getManager();
        $repository = $em->getRepository('AppBundle:Shipping');
        # select wanted item from shipping table to delete it
        $ship = $repository->findBy(array('cart' => $cart));
        # Fetch all them using foeach loop and delete them
        foreach ($ship as $one_prod)
        {
            # Remove item from db
            $em->remove($one_prod);
            $em->flush();
        }
        $cart_repository = $em->getRepository('AppBundle:Cart');
        $one_cart = $cart_repository->findOne(['id' => $cart]);
        $em->remove($one_cart);
        $em->flush();
        return $this->redirect($this->generateUrl('view_cart'));
    }
}

这是我的购物车实体代码:

<?php
namespace AppBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use AppBundle\Entity\Shipping;

#use AppBundle\Entity\User;
#use AppBundle\Entity\Product;
/**
 * @ORM\Entity
 * @ORM\Table(name="cart")
 */
class Cart
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;
    /**
     * @ORM\Column(type="decimal", scale=2)
     */
    private $total_price;

    /**
     * @ORM\Column(type="integer")
     */
    private $quantity;
    /**
     * @ORM\OneToOne(targetEntity="User", inversedBy="cart")
     */
    private $user;
    /** @ORM\OneToMany(targetEntity="Shipping", mappedBy="cart") */
    protected $cartProducts;
    /**
     * Constructor
     */
    public function __construct()
    {
        $this->cartProducts = new ArrayCollection();
    }
    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }
    /**
     * Set total_price
     *
     * @param string $totalPrice
     * @return Cart
     */
    public function setTotalPrice($totalPrice)
    {
        $this->total_price = $totalPrice;
        return $this;
    }
    /**
     * Get total_price
     *
     * @return string
     */
    public function getTotalPrice()
    {
        return $this->total_price;
    }
    /**
     * Set quantity
     *
     * @param integer $quantity
     * @return Cart
     */
    public function setQuantity($quantity)
    {
        $this->quantity = $quantity;
        return $this;
    }
    /**
     * Get quantity
     *
     * @return integer
     */
    public function getQuantity()
    {
        return $this->quantity;
    }
    /**
     * Set user
     *
     * @param \AppBundle\Entity\User $user
     * @return Cart
     */
    public function setUser(\AppBundle\Entity\User $user = null)
    {
        $this->user = $user;
        return $this;
    }
    /**
     * Get user
     *
     * @return \AppBundle\Entity\User
     */
    public function getUser()
    {
        return $this->user;
    }
    /**
     * Add cartProducts
     *
     * @param Shipping $cartProducts
     * @return Collection
     */
    public function addCartProduct(array $cartProducts)
    {
        $this->cartProducts[] = $cartProducts;
        return $this;
    }
    /**
     * Remove cartProducts
     *
     * @param Shipping $cartProducts
     */
    public function removeCartProduct(array $cartProducts)
    {
        $this->cartProducts->removeElement($cartProducts);
    }
    /**
     * Get cartProducts
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getCartProducts()
    {
        return $this->cartProducts;
    }
}

和我的运输实体:

<?php
// src/AppBundle/Entity/User.php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
#use AppBundle\Entity\User;
#use AppBundle\Entity\Product;
/**
 * @ORM\Entity
 * @ORM\Table(name="shipping")
 */
class Shipping
{

    /**
     * @ORM\Column(type="integer")
     */
    private $quantity;
    /**
     * @ORM\Id()
     * @ORM\ManyToOne(targetEntity="Product", inversedBy="cartProducts")
     */
    protected $product;
    /**
     * @ORM\Id()
     * @ORM\ManyToOne(targetEntity="Cart", inversedBy="cartProducts")
     */
    protected $cart;

    /**
     * Set product
     *
     * @param \AppBundle\Entity\Product $product
     * @return Shipping
     */
    public function setProduct(\AppBundle\Entity\Product $product)
    {
        $this->product = $product;
        return $this;
    }
    /**
     * Get product
     *
     * @return \AppBundle\Entity\Product
     */
    public function getProduct()
    {
        return $this->product;
    }
    /**
     * Set cart
     *
     * @param \AppBundle\Entity\Cart $cart
     * @return Shipping
     */
    public function setCart(\AppBundle\Entity\Cart $cart)
    {
        $this->cart = $cart;
        return $this;
    }
    /**
     * Get cart
     *
     * @return \AppBundle\Entity\Cart
     */
    public function getCart()
    {
        return $this->cart;
    }
    /**
     * Set quantity
     *
     * @param integer $quantity
     * @return Shipping
     */
    public function setQuantity($quantity)
    {
        $this->quantity = $quantity;
        return $this;
    }
    /**
     * Get quantity
     *
     * @return integer
     */
    public function getQuantity()
    {
        return $this->quantity;
    }
}

共有1个答案

柯瀚海
2023-03-14

通过使用->select('your join entity'、'alias')方法,尝试使用带有->select()的Decision query builder从查询中检索数组而不是对象

 类似资料:
  • 我使用solcialite登录Laravel通过Gihub,但有问题登录。我得到一个错误:Symfony\组件\调试\异常\FatalThrowableError(E_RECOVERABLE_ERROR)类型错误:参数1传递给照明\Auth\SessionGuard::登录()必须实现接口照明\合同\Auth\身份验证,空给定,调用 /var/www/html/testio/vendor/lara

  • 有时对一个类的某些方面进行 参数化(parameterize)是很有用的。例如, 你可能需要管理不同版本的 gem 软件包,既可以为每一种版本创建分离的单独的类, 也可以使用继承和覆盖,为一个类传递一个版本号作为参数。 操作步骤 声明参数作为如下类定义的一部分: class eventmachine( $version ) { package { "eventmachine": pro

  • 我们正在使用依赖于Symfony的Contao 4.7.7,出于某种原因,我们收到了以下致命错误,但不确定这是如何出现的。 在此事件中:内核传递错误的事件 如何解决这个问题? 致命错误:未捕获类型错误:传递给Symfony\Component\EventDispatcher\EventDispatcher::dispatch()的参数2必须是Symfony\Component\EventDispa

  • 我得到这个错误,而试图登录API Symfony\组件\调试\异常\FatalThrowableError:传递给Tymon\JWTAuth\JWTGuar的参数1d::登录()必须是Tymon\JWTAuth\合同\JWT主题的实例,应用程序的实例\用户给定,在文件 /home/scrixmll的第307行 /home/scrixmll/apiadmin.silexsecure.com/vend

  • 我在我的项目中使用Gson。但它返回给我错误 我得到一个服务器响应,如下所示 我有一个错误,需要一个字符串,但是BEGIN_OBJECT 我应该如何处理这个异常?? 我没有访问数据库的权限,因为我使用API

  • 所以我试着做下面这样的事情 并且定义为 当尝试编译代码时,clang给出错误。我发现这是因为你不能从lambda推断出类型。 所以这实际上是正确的,因为我实际上希望的参数类型是从的参数推导出的类型。 所以我的问题是,有没有可能排除参数的推导,而只是使用的推导类型?