类型错误:传递给Doctrine\Common\Collections\ArrayCollection :: __ construct()的参数1必须为数组类型,给定对象 [英] Type error: Argument 1 passed to Doctrine\Common\Collections\ArrayCollection::__construct() must be of the type array, object given

查看:112
本文介绍了类型错误:传递给Doctrine\Common\Collections\ArrayCollection :: __ construct()的参数1必须为数组类型,给定对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

实际上...或多或少,我知道我的问题在哪里。
我在某个特定的控制器中收到此错误,在该控制器中尝试 persist($ object) ...

Actually... more or less I know where is my problem. I'm receiving this error in a particular controller where I try to persist($object)...

实际上,我正在为我开发一个Webapp,以便对我正在阅读的所有图书进行注册。.为此,我使用了Google Books API。因此,我有下一个实体:

Actually I'm developing a webapp for me to have a register to all my books I'm reading.. and I use Google Books API for that. So, I have the next Entities:


  • Admin

  • Users

  • 书籍

  • 类别

  • Admin
  • Users
  • Books
  • Categories

我在考虑 db ,我想要一个带有 user_id,book_id
的表,所以我决定做一个 ManyToMany 但是,我不知道这是不是.. (因为我的熟人将要使用它)

I was thinking about the db and I wanted a table with user_id, book_id so I decided to do a ManyToMany but, I don't know if this is the way.. or not. (Because my familiars are going to use it)

它必须像许多用户可以拥有同一本书

It has to be like many users can have the same book and a user can have many books obviusly.

因此,我得到的错误是因为我没有很好地实现 ManyToMany ... 我在 Controller Entities

So, the error I'm getting I guess it's because I'm not implementing well done the ManyToMany... I write below the Controller and Entities

用户的位置:

/**
 * @ORM\Entity
 * @ORM\Table(name="Users")
 * @ORM\Entity(repositoryClass="UsersRepository")
 * @UniqueEntity("username")
 * @UniqueEntity("email")
 */
class Users implements UserInterface, \Serializable
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\Column(type="text")
     * @Assert\NotBlank()
     */
    private $name;

    /**
     * @ORM\Column(type="text")
     * @Assert\NotBlank()
     */
    private $lastname;

    /**
     * @ORM\Column(type="text")
     * @Assert\NotBlank()
     */
    private $username;

    /**
     * @ORM\Column(type="string", length=255, unique=true)
     * @Assert\NotBlank()
     * @Assert\Email()
     */
    private $email;

    /**
     *
     * @Assert\Length(max=4096)
     */
    private $plainPassword;

    /**
     *
     * @ORM\Column(type="string", length=64)
     */
    private $password;

    /**
     * @ORM\Column(type="text")
     * @Assert\NotBlank()
     */
    private $language;

    /**
     * @ORM\Column(type="boolean")
     */
    private $isActive;


    /*****************
     * Users constructor.
     */
    public function __construct() {
        $this->language = 'es';
        $this->isActive = true;
    }

    /**
     * @return mixed
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @param mixed $id
     */
    public function setId($id)
    {
        $this->id = $id;
    }

    /**
     * @return mixed
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @param mixed $name
     */
    public function setName($name)
    {
        $this->name = $name;
    }

    /**
     * @return mixed
     */
    public function getLastname()
    {
        return $this->lastname;
    }

    /**
     * @param mixed $lastname
     */
    public function setLastname($lastname)
    {
        $this->lastname = $lastname;
    }

    /**
     * @return mixed
     */
    public function getUsername()
    {
        return $this->username;
    }

    /**
     * @param mixed $username
     */
    public function setUsername($username)
    {
        $this->username = $username;
    }

    /**
     * @return mixed
     */
    public function getEmail()
    {
        return $this->email;
    }

    /**
     * @param mixed $email
     */
    public function setEmail($email)
    {
        $this->email = $email;
    }

    /**
     * @return mixed
     */
    public function getPlainPassword()
    {
        return $this->plainPassword;
    }

    /**
     * @param mixed $plainPassword
     */
    public function setPlainPassword($plainPassword)
    {
        $this->plainPassword = $plainPassword;
    }

    /**
     * @return mixed
     */
    public function getPassword()
    {
        return $this->password;
    }

    /**
     * @param mixed $password
     */
    public function setPassword($password)
    {
        $this->password = $password;
    }

    /**
     * @return mixed
     */
    public function getLanguage()
    {
        return $this->language;
    }

    /**
     * @param mixed $language
     */
    public function setLanguage($language)
    {
        $this->language = $language;
    }

    /**
     * @return mixed
     */
    public function getIsActive()
    {
        return $this->isActive;
    }

    /**
     * @param mixed $isActive
     */
    public function setIsActive($isActive)
    {
        $this->isActive = $isActive;
    }

    //implementaciones de la interface

    public function getSalt()
    {
        // you *may* need a real salt depending on your encoder
        // see section on salt below
        return null;
    }

    public function getRoles()
    {
        return array('ROLE_USER');
    }

    public function eraseCredentials()
    {
    }

    /** @see \Serializable::serialize() */
    public function serialize()
    {
        return serialize(array(
            $this->id,
            $this->username,
            $this->password,
            $this->isActive,
        ));
    }

    /** @see \Serializable::unserialize() */
    public function unserialize($serialized)
    {
        list (
            $this->id,
            $this->username,
            $this->password,
            $this->isActive,
            ) = unserialize($serialized);
    }
}

书本如下:

/**
 * @ORM\Entity
 * @ORM\Table(name="Book")
 * @ORM\Entity(repositoryClass="BookRepository")
 */
class Book
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\Column(type="text")
     * @Assert\NotBlank()
     */
    private $title;

    /**
     * @ORM\Column(type="text")
     * @Assert\NotBlank()
     */
    private $author;

    /**
     * @ORM\Column(type="text")
     */
    private $language;

    /**
     * @ORM\Column(type="text")
     * @Assert\NotBlank()
     */
    private $genre;

    /**
     * @ORM\Column(type="integer")
     * @Assert\NotBlank()
     */
    private $price;

    /**
     * @ORM\Column(type="text")
     */
    private $pages;

    /**
     * @ORM\Column(type="text")
     * @Assert\NotBlank()
     */
    private $synopsis;

    /**
     * @ORM\Column(type="text", nullable=true)
     */
    private $rate;

    /**
     * @ORM\Column(type="text")
     */
    private $id_google;

    /**
     * @ORM\ManyToMany(targetEntity="Users", mappedBy="books")
     */
    private $users;



    /*****************
     * Book constructor.
     */
    public function __construct() {
        $this->users    = new ArrayCollection();
    }

    /**
     * @return mixed
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @param mixed $id
     */
    public function setId($id)
    {
        $this->id = $id;
    }

    /**
     * @return mixed
     */
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * @param mixed $title
     */
    public function setTitle($title)
    {
        $this->title = $title;
    }

    /**
     * @return mixed
     */
    public function getAuthor()
    {
        return $this->author;
    }

    /**
     * @param mixed $author
     */
    public function setAuthor($author)
    {
        $this->author = $author;
    }

    /**
     * @return mixed
     */
    public function getLanguage()
    {
        return $this->language;
    }

    /**
     * @param mixed $language
     */
    public function setLanguage($language)
    {
        $this->language = $language;
    }

    /**
     * @return mixed
     */
    public function getGenre()
    {
        return $this->genre;
    }

    /**
     * @param mixed $genre
     */
    public function setGenre($genre)
    {
        $this->genre = $genre;
    }

    /**
     * @return mixed
     */
    public function getPrice()
    {
        return $this->price;
    }

    /**
     * @param mixed $price
     */
    public function setPrice($price)
    {
        $this->price = $price;
    }

    /**
     * @return mixed
     */
    public function getPages()
    {
        return $this->pages;
    }

    /**
     * @param mixed $pages
     */
    public function setPages($pages)
    {
        $this->pages = $pages;
    }

    /**
     * @return mixed
     */
    public function getSynopsis()
    {
        return $this->synopsis;
    }

    /**
     * @param mixed $synopsis
     */
    public function setSynopsis($synopsis)
    {
        $this->synopsis = $synopsis;
    }

    /**
     * @return mixed
     */
    public function getRate()
    {
        return $this->rate;
    }

    /**
     * @param mixed $rate
     */
    public function setRate($rate)
    {
        $this->rate = $rate;
    }

    /**
     * @return mixed
     */
    public function getIdGoogle()
    {
        return $this->id_google;
    }

    /**
     * @param mixed $id_google
     */
    public function setIdGoogle($id_google)
    {
        $this->id_google = $id_google;
    }

    /**
     * @return mixed
     */
    public function getUsers()
    {
        return $this->users;
    }

    /**
     * @param mixed $users
     */
    public function setUsers(Users $users = null)
    {
        $this->users = $users;
    }

    /**
     * Add user
     *
     * @param \AppBundle\Entity\Users $user
     *
     * @return Book
     */
    public function addUser(Users $user)
    {
        $this->users[] = $user;

        return $this;
    }

    /**
     * Remove user
     *
     * @param \AppBundle\Entity\Users $user
     */
    public function removeUser(Users $user)
    {
        $this->users->removeElement($user);
    }
}

LibraryController

class LibraryController extends BaseController
{
    private $APIkey = "&key=" . "AIzaSyAN638WbYe1vOfGya989p7ZbfXnPzBLfkg";
    /**
     * @Route ("/libreria", name="libreria")
     */
    public function getLibreria(){

        $securityContext = $this->container->get('security.authorization_checker');
        if ($securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
            $em = $this->getDoctrine()->getManager();

            $user = $this->get('security.token_storage')->getToken()->getUser();

            $this->addData('user', $user);
            return $this->render('AppBundle:libreria:libreria.html.twig', $this->getData());
        }

        return $this->redirect("login");
    }

    /**
     * Adds to the library the requested book
     * @Route ("/libreria/addBook/{id_google}", name="addBook")
     */
    public function addBook($id_google){

        $securityContext = $this->container->get('security.authorization_checker');
        if ($securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
            $em   = $this->getDoctrine()->getManager();

            $user = $this->get('security.token_storage')->getToken()->getUser();

            $infoBook   = $this->getBookFromAPI($id_google); // Cogemos toda la información del libro en cuestión
            $vInfo      = $infoBook['volumeInfo']; // Para ahorrarnos código y usar este subarray de manera practica
            $book       = new Book();


            /**
             * Hacemos los seters pertinentes para poner el contenido en el libro
             * y dejarlo listo para poder hacer un flush
             */
            $book->setTitle($vInfo['title']);
            $book->setAuthor($vInfo['authors'][0]);
            $book->setLanguage($vInfo['language']);
            $book->setGenre($vInfo['categories'][0]);
            $book->setPrice($infoBook['saleInfo']['retailPrice']['amount']);
            $book->setPages($vInfo['printedPageCount']);
            $book->setSynopsis($vInfo['description']);

            if($vInfo['averageRating']){
                $book->setRate($vInfo['averageRating']);
            }

            $book->setIdGoogle($id_google);
            $book->setUsers($user);

            // Guardamos el libro en la bbdd
            $em->persist($book);
            $em->flush();

            $this->sendResponseStatus('OK');

            // Generamos los datos para la respuesta ajax
            return new JSONResponse($this->getData());
        }

        return $this->redirect("login");
    }


    // Coge la información de un libro gracias a su id
    public function getBookFromAPI($id){
        // Instancia del BuzzBundle para peticiones HTTP externas
        $buzz = $this->container->get('buzz');

        // Resultado de la peticion HTTP 'GET'
        $responseAPI = $buzz->get('https://www.googleapis.com/books/v1/volumes/'.$id);
        $jsonLibro = $responseAPI->getContent();

        return $this->transformarStringToArray($jsonLibro);
    }


    // Se usa para hacer que el String devuelto por la API de Google sea un array
    public function transformarStringToArray($string){
        $stringDecoded = json_decode($string);
        $array = json_decode(json_encode($stringDecoded), true);

        return $array;

    }
}

所以,我猜错了当我尝试保留 db 的原因是因为实施了某些错误的内容...

So, the error appears I guess when I try to persist the db because there is something bad implemented...

任何提示或解决方案?

谢谢大家!祝你有美好的一天!

Victor

推荐答案

$ book-> setUsers($ user); $ book-> addUser($ user);

通常,方法 setUsers 无效

public function setUsers(Users $users = null)
{
    $this->users = $users;
}

在构造函数中初始化后,不得重新定义此属性。您只能在其中添加或删除元素,但是分配新值将破坏该学说的功能。

You must not redefine this property after being initialized in the constructor. You can only add or remove elements from it, but assigning new value will break doctrine's functionality.

这篇关于类型错误:传递给Doctrine\Common\Collections\ArrayCollection :: __ construct()的参数1必须为数组类型,给定对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆