类型错误:传递给Doctrine \ Common \ Collections \ ArrayCollection :: __ construct()的参数1必须是类型数组,对象为

时间:2016-09-22 12:04:35

标签: php symfony doctrine-orm controller entity

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

实际上我正在开发一个网络应用程序,让我可以注册我正在阅读的所有书籍。我使用Google Books API。所以,我有下一个实体:

  • 管理
  • 用户
  • 图书
  • 类别

我正在考虑db,我想要一张user_id, book_id的表格 所以我决定做一个ManyToMany但是,我不知道这是不是...... (Because my familiars are going to use it)

必须像许多用户可以拥有相同的书一样,并且用户可以有很多书。

所以,我猜错了,因为我在ManyToMany... ControllerEntities下面写的/** * @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);
    }
}

和图书就像:

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

所以,当我尝试坚持<UserControl x:Class="Chess_Interface.UserControls.PositionControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:Chess_Interface.UserControls" xmlns:m="clr-namespace:Chess_Interface" mc:Ignorable="d" d:DesignHeight="450" d:DesignWidth="450"> <Grid> <UniformGrid Rows="8" Columns="1" Height="400" HorizontalAlignment="Left"> <Label Content="8" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Padding="0" /> <Label Content="7" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Padding="0" /> <Label Content="6" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Padding="0" /> <Label Content="5" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Padding="0" /> <Label Content="4" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Padding="0" /> <Label Content="3" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Padding="0" /> <Label Content="2" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Padding="0" /> <Label Content="1" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Padding="0" /> </UniformGrid> <UniformGrid Rows="8" Columns="1" Height="400" HorizontalAlignment="Right"> <Label Content="8" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Padding="0" /> <Label Content="7" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Padding="0" /> <Label Content="6" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Padding="0" /> <Label Content="5" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Padding="0" /> <Label Content="4" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Padding="0" /> <Label Content="3" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Padding="0" /> <Label Content="2" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Padding="0" /> <Label Content="1" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Padding="0" /> </UniformGrid> <UniformGrid Rows="1" Columns="8" Width="400" VerticalAlignment="Top"> <Label Content="A" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Padding="0" /> <Label Content="B" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Padding="0" /> <Label Content="C" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Padding="0" /> <Label Content="D" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Padding="0" /> <Label Content="E" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Padding="0" /> <Label Content="F" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Padding="0" /> <Label Content="G" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Padding="0" /> <Label Content="H" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Padding="0" /> </UniformGrid> <UniformGrid Rows="1" Columns="8" Width="400" VerticalAlignment="Bottom"> <Label Content="A" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Padding="0" /> <Label Content="B" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Padding="0" /> <Label Content="C" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Padding="0" /> <Label Content="D" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Padding="0" /> <Label Content="E" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Padding="0" /> <Label Content="F" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Padding="0" /> <Label Content="G" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Padding="0" /> <Label Content="H" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Padding="0" /> </UniformGrid> <Grid x:Name="ChessBoard" Width="400" Height="400" VerticalAlignment="Center" HorizontalAlignment="Center" MouseLeftButtonDown="ChessBoard_MouseLeftButtonDown" MouseLeftButtonUp="ChessBoard_MouseLeftButtonUp" > <Grid.ColumnDefinitions > <ColumnDefinition Width="*" SharedSizeGroup="SizeGroup"/> <ColumnDefinition Width="*" SharedSizeGroup="SizeGroup"/> <ColumnDefinition Width="*" SharedSizeGroup="SizeGroup"/> <ColumnDefinition Width="*" SharedSizeGroup="SizeGroup"/> <ColumnDefinition Width="*" SharedSizeGroup="SizeGroup"/> <ColumnDefinition Width="*" SharedSizeGroup="SizeGroup"/> <ColumnDefinition Width="*" SharedSizeGroup="SizeGroup"/> <ColumnDefinition Width="*" SharedSizeGroup="SizeGroup"/> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="*" SharedSizeGroup="SizeGroup"/> <RowDefinition Height="*" SharedSizeGroup="SizeGroup"/> <RowDefinition Height="*" SharedSizeGroup="SizeGroup"/> <RowDefinition Height="*" SharedSizeGroup="SizeGroup"/> <RowDefinition Height="*" SharedSizeGroup="SizeGroup"/> <RowDefinition Height="*" SharedSizeGroup="SizeGroup"/> <RowDefinition Height="*" SharedSizeGroup="SizeGroup"/> <RowDefinition Height="*" SharedSizeGroup="SizeGroup"/> </Grid.RowDefinitions> <Border Grid.Row="0" Grid.Column="0" Background="White"></Border> <Border Grid.Row="0" Grid.Column="1" Background="Brown"></Border> <Border Grid.Row="0" Grid.Column="2" Background="White"></Border> <Border Grid.Row="0" Grid.Column="3" Background="Brown"></Border> <Border Grid.Row="0" Grid.Column="4" Background="White"></Border> <Border Grid.Row="0" Grid.Column="5" Background="Brown"></Border> <Border Grid.Row="0" Grid.Column="6" Background="White"></Border> <Border Grid.Row="0" Grid.Column="7" Background="Brown"></Border> <Border Grid.Row="1" Grid.Column="0" Background="Brown"></Border> <Border Grid.Row="1" Grid.Column="1" Background="White"></Border> <Border Grid.Row="1" Grid.Column="2" Background="Brown"></Border> <Border Grid.Row="1" Grid.Column="3" Background="White"></Border> <Border Grid.Row="1" Grid.Column="4" Background="Brown"></Border> <Border Grid.Row="1" Grid.Column="5" Background="White"></Border> <Border Grid.Row="1" Grid.Column="6" Background="Brown"></Border> <Border Grid.Row="1" Grid.Column="7" Background="White"></Border> <Border Grid.Row="2" Grid.Column="0" Background="White"></Border> <Border Grid.Row="2" Grid.Column="1" Background="Brown"></Border> <Border Grid.Row="2" Grid.Column="2" Background="White"></Border> <Border Grid.Row="2" Grid.Column="3" Background="Brown"></Border> <Border Grid.Row="2" Grid.Column="4" Background="White"></Border> <Border Grid.Row="2" Grid.Column="5" Background="Brown"></Border> <Border Grid.Row="2" Grid.Column="6" Background="White"></Border> <Border Grid.Row="2" Grid.Column="7" Background="Brown"></Border> <Border Grid.Row="3" Grid.Column="0" Background="Brown"></Border> <Border Grid.Row="3" Grid.Column="1" Background="White"></Border> <Border Grid.Row="3" Grid.Column="2" Background="Brown"></Border> <Border Grid.Row="3" Grid.Column="3" Background="White"></Border> <Border Grid.Row="3" Grid.Column="4" Background="Brown"></Border> <Border Grid.Row="3" Grid.Column="5" Background="White"></Border> <Border Grid.Row="3" Grid.Column="6" Background="Brown"></Border> <Border Grid.Row="3" Grid.Column="7" Background="White"></Border> <Border Grid.Row="4" Grid.Column="0" Background="White"></Border> <Border Grid.Row="4" Grid.Column="1" Background="Brown"></Border> <Border Grid.Row="4" Grid.Column="2" Background="White"></Border> <Border Grid.Row="4" Grid.Column="3" Background="Brown"></Border> <Border Grid.Row="4" Grid.Column="4" Background="White"></Border> <Border Grid.Row="4" Grid.Column="5" Background="Brown"></Border> <Border Grid.Row="4" Grid.Column="6" Background="White"></Border> <Border Grid.Row="4" Grid.Column="7" Background="Brown"></Border> <Border Grid.Row="5" Grid.Column="0" Background="Brown"></Border> <Border Grid.Row="5" Grid.Column="1" Background="White"></Border> <Border Grid.Row="5" Grid.Column="2" Background="Brown"></Border> <Border Grid.Row="5" Grid.Column="3" Background="White"></Border> <Border Grid.Row="5" Grid.Column="4" Background="Brown"></Border> <Border Grid.Row="5" Grid.Column="5" Background="White"></Border> <Border Grid.Row="5" Grid.Column="6" Background="Brown"></Border> <Border Grid.Row="5" Grid.Column="7" Background="White"></Border> <Border Grid.Row="6" Grid.Column="0" Background="White"></Border> <Border Grid.Row="6" Grid.Column="1" Background="Brown"></Border> <Border Grid.Row="6" Grid.Column="2" Background="White"></Border> <Border Grid.Row="6" Grid.Column="3" Background="Brown"></Border> <Border Grid.Row="6" Grid.Column="4" Background="White"></Border> <Border Grid.Row="6" Grid.Column="5" Background="Brown"></Border> <Border Grid.Row="6" Grid.Column="6" Background="White"></Border> <Border Grid.Row="6" Grid.Column="7" Background="Brown"></Border> <Border Grid.Row="7" Grid.Column="0" Background="Brown"></Border> <Border Grid.Row="7" Grid.Column="1" Background="White"></Border> <Border Grid.Row="7" Grid.Column="2" Background="Brown"></Border> <Border Grid.Row="7" Grid.Column="3" Background="White"></Border> <Border Grid.Row="7" Grid.Column="4" Background="Brown"></Border> <Border Grid.Row="7" Grid.Column="5" Background="White"></Border> <Border Grid.Row="7" Grid.Column="6" Background="Brown"></Border> <Border Grid.Row="7" Grid.Column="7" Background="White"></Border> </Grid> </Grid> 时,我猜错了,因为实施了一些不好的事情......

任何线索或解决方案?

感谢大家!祝你有愉快的一天!

维克多

1 个答案:

答案 0 :(得分:3)

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

而且,通常,方法setUsers无效

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

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