Я уже несколько дней сражаюсь с этим небольшим учебным проектом. Это интерфейс базы данных регистрации заголовков DVD. Существует два объекта: «Пользователи и заголовки». Я хочу иметь возможность сохранять / извлекать в базу данных идентификатор пользователя, который сделал запись заголовка.
Вот сведения об объединении объектов:
class Titles { //... /** * @ORM\ManyToOne(targetEntity="Users", inversedBy="titles") * @ORM\JoinColumn(name="user_id", referencedColumnName="id") */ protected $addedBy; //... } class Users { //... /** * * @ORM\OneToMany(targetEntity="Titles", mappedBy="addedBy") */ protected $titles = array(); //... }
При попытке отправить форму я получаю следующую ошибку:
Warning: spl_object_hash() expects parameter 1 to be object, integer given in C:\xampp\htdocs\dvdLogger\vendor\doctrine\orm\lib\Doctrine \ORM\UnitOfWork.php line 1389
Вот метод formBuilder:
public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('title') ->add('genre'); }
и метод addAction:
public function addAction() { // add title to db $title = new Titles(); $form = $this->createForm(new TitlesType(), $title); $request = $this->getRequest(); $form->bind($request); if ($form->isValid()) { // persist to db $em = $this->getDoctrine() ->getManager(); $em->persist($title); $em->flush(); return $this->redirect($this->generateUrl('dvdLoggerdvdBundle_homepage')); } return $this->render('dvdLoggerdvdBundle:Page:add.html.twig', array( 'form' => $form->createView() )); }
Любые советы относительно отладки будут оценены. Я все еще привык к Симфонию.
обновление 1
весь титул:
/** * @ORM\Entity * @ORM\Entity(repositoryClass="dvdLogger\dvdBundle\Entity\Repository\loggerRepository") * @ORM\Table(name="titles") */ class Titles { /** * @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /** * @ORM\Column(type="string") */ protected $title; /** * @ORM\Column(type="string") */ protected $genre; /** * @ORM\Column(type="string") * */ protected $dateAdded; /** * @ORM\ManyToOne(targetEntity="Users", inversedBy="titles") * @ORM\JoinColumn(name="user_id", referencedColumnName="id") */ protected $addedBy; public function __construct() { $this->user_id = null; // Default value for column user_id $this->children = new \Doctrine\Common\Collections\ArrayCollection(); $this->dateAdded = date("F j, Y, g:ia"); $this->addedBy = 1; } /** * Set genre * * @param string $genre * @return Titles */ public function setGenre($genre) { $this->genre = $genre; return $this; } /** * Get genre * * @return string */ public function getGenre() { return $this->genre; } /** * Set dateAdded * * @param string $dateAdded * @return Titles */ public function setDateAdded($dateAdded) { $this->dateAdded = $dateAdded; return $this; } /** * Get dateAdded * * @return string */ public function getDateAdded() { return $this->dateAdded; } /** * Set addedBy * * @param integer $addedBy * @return Titles */ public function setAddedBy($addedBy) { $this->addedBy = $addedBy; return $this; } /** * Get addedBy * * @return integer */ public function getAddedBy() { return $this->addedBy; } /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set title * * @param string $title * @return Titles */ public function setTitle($title) { $this->title = $title; return $this; } /** * Get title * * @return string */ public function getTitle() { return $this->title; } }
и пользовательский объект:
/** * @ORM\Entity * @ORM\Entity(repositoryClass="dvdLogger\dvdBundle\Entity\Repository\usersRepository") * @ORM\Table(name="users") */ class Users { /** * @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /** * @ORM\Column(type="string") */ protected $username; /** * @ORM\Column(type="integer") */ protected $rank; /** * @ORM\Column(type="string") */ protected $email; /** * @ORM\Column(type="datetime") */ protected $lastLogged; /** * * @ORM\OneToMany(targetEntity="Titles", mappedBy="addedBy") */ protected $titles = array(); /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Constructor */ public function __construct() { $this->titles = new \Doctrine\Common\Collections\ArrayCollection(); } /** * Add titles * * @param \dvdLogger\dvdBundle\Entity\Titles $titles * @return Users */ public function addTitle(\dvdLogger\dvdBundle\Entity\Titles $titles) { $this->titles[] = $titles; return $this; } /** * Remove titles * * @param \dvdLogger\dvdBundle\Entity\Titles $titles */ public function removeTitle(\dvdLogger\dvdBundle\Entity\Titles $titles) { $this->titles->removeElement($titles); } /** * Get titles * * @return \Doctrine\Common\Collections\Collection */ public function getTitles() { return $this->titles; } /** * Set username * * @param string $username * @return Users */ public function setUsername($username) { $this->username = $username; return $this; } /** * Get username * * @return string */ public function getUsername() { return $this->username; } /** * Set rank * * @param integer $rank * @return Users */ public function setRank($rank) { $this->rank = $rank; return $this; } /** * Get rank * * @return integer */ public function getRank() { return $this->rank; } /** * Set email * * @param string $email * @return Users */ public function setEmail($email) { $this->email = $email; return $this; } /** * Get email * * @return string */ public function getEmail() { return $this->email; } /** * Set lastLogged * * @param \DateTime $lastLogged * @return Users */ public function setLastLogged($lastLogged) { $this->lastLogged = $lastLogged; return $this; } /** * Get lastLogged * * @return \DateTime */ public function getLastLogged() { return $this->lastLogged; } }
Трассировки стека
in C:\xampp\htdocs\dvdLogger\vendor\doctrine\orm\lib\Doctrine\ORM\UnitOfWork.php at line 1389 + at ErrorHandler ->handle ('2', 'spl_object_hash() expects parameter 1 to be object, integer given', 'C:\xampp\htdocs\dvdLogger\vendor\doctrine\orm\lib\Doctrine\ORM\UnitOfWork.php', '1389', array('entity' => '1', 'assume' => '2')) at spl_object_hash ('1') in C:\xampp\htdocs\dvdLogger\vendor\doctrine\orm\lib\Doctrine\ORM\UnitOfWork.php at line 1389 + at UnitOfWork ->getEntityState ('1', '2') in C:\xampp\htdocs\dvdLogger\vendor\doctrine\orm\lib\Doctrine\ORM\UnitOfWork.php at line 788 + at UnitOfWork ->computeAssociationChanges (array('fieldName' => 'addedBy', 'joinColumns' => array(array('name' => 'user_id', 'unique' => false, 'nullable' => true, 'onDelete' => null, 'columnDefinition' => null, 'referencedColumnName' => 'id')), 'cascade' => array(), 'inversedBy' => 'titles', 'targetEntity' => 'dvdLogger\dvdBundle\Entity\Users', 'fetch' => '2', 'type' => '2', 'mappedBy' => null, 'isOwningSide' => true, 'sourceEntity' => 'dvdLogger\dvdBundle\Entity\Titles', 'isCascadeRemove' => false, 'isCascadePersist' => false, 'isCascadeRefresh' => false, 'isCascadeMerge' => false, 'isCascadeDetach' => false, 'sourceToTargetKeyColumns' => array('user_id' => 'id'), 'joinColumnFieldNames' => array('user_id' => 'user_id'), 'targetToSourceKeyColumns' => array('id' => 'user_id'), 'orphanRemoval' => false), '1') in C:\xampp\htdocs\dvdLogger\vendor\doctrine\orm\lib\Doctrine\ORM\UnitOfWork.php at line 687 + at UnitOfWork ->computeChangeSet (object(ClassMetadata), object(Titles)) in C:\xampp\htdocs\dvdLogger\vendor\doctrine\orm\lib\Doctrine\ORM\UnitOfWork.php at line 404 + at UnitOfWork ->computeScheduleInsertsChangeSets () in C:\xampp\htdocs\dvdLogger\vendor\doctrine\orm\lib\Doctrine\ORM\UnitOfWork.php at line 711 + at UnitOfWork ->computeChangeSets () in C:\xampp\htdocs\dvdLogger\vendor\doctrine\orm\lib\Doctrine\ORM\UnitOfWork.php at line 297 + at UnitOfWork ->commit (null) in C:\xampp\htdocs\dvdLogger\vendor\doctrine\orm\lib\Doctrine\ORM\EntityManager.php at line 389 + at EntityManager ->flush () in C:\xampp\htdocs\dvdLogger\src\dvdLogger\dvdBundle\Controller\PageController.php at line 48 + at PageController ->addAction () at call_user_func_array (array(object(PageController), 'addAction'), array()) in C:\xampp\htdocs\dvdLogger\app\bootstrap.php.cache at line 2969 + at HttpKernel ->handleRaw (object(Request), '1') in C:\xampp\htdocs\dvdLogger\app\bootstrap.php.cache at line 2931 + at HttpKernel ->handle (object(Request), '1', true) in C:\xampp\htdocs\dvdLogger\app\bootstrap.php.cache at line 3080 + at ContainerAwareHttpKernel ->handle (object(Request), '1', true) in C:\xampp\htdocs\dvdLogger\app\bootstrap.php.cache at line 2330 + at Kernel ->handle (object(Request)) in C:\xampp\htdocs\dvdLogger\web\app_dev.php at line 28 +
обновление 2
public function indexAction() { $em = $this->getDoctrine() ->getManager(); $titles = $em->getRepository('dvdLoggerdvdBundle:Titles')->getAllTitles(); return $this->render('dvdLoggerdvdBundle:Page:index.html.twig', array( 'titles' => $titles )); }
затем getAllTitles из репо
public function getAllTitles() { // view all records in db $titles = $this->createQueryBuilder('t') ->select('t, u') ->leftJoin('t.addedBy', 'u') ->addOrderBy('t.title', 'DESC'); return $titles->getQuery()->getResult(); }
Я предполагаю, что это проблема, ее сосание массивной памяти при запросе dbase, но я не могу понять, почему
Удалите эту строку полностью из вашего метода __construct()
в Title
.
$this->addedBy = 1;
И сделайте это в своем PageController
.
$em = $this->getDoctrine()->getManager(); $title->setAddedBy($this->getUser()); $em->persist($title); $em->flush();