2016-08-09 2 views
1

Я пытаюсь вставить данные в БД, но он показывает ошибку, как этот Image of the error Ошибка при вставке в БД с помощью Doctrine ORM

Моя модель Entity

Request.php

is here `<?php 


namespace EvolisClientRequest\Model\Entities; 

use Doctrine\ORM\Mapping as ORM; 

/** 
* @ORM\Entity 
*/ 
class Request 
{ 
    /** 
    * @var \Ramsey\Uuid\Uuid 
    * @ORM\Id 
    * @ORM\Column(type="uuid") 
    * @ORM\GeneratedValue(strategy="CUSTOM") 
    * @ORM\CustomIdGenerator(class="Ramsey\Uuid\Doctrine\UuidGenerator") 
    */ 
    protected $id; 

    /** 
    * @ORM\ManyToMany(targetEntity="Salesperson", inversedBy="request") 
    * @ORM\JoinTable(name="request_salesperson") 
    * @var Salesperson 
    */ 
    private $salesperson; 

    /** 
    * @ORM\ManyToOne(targetEntity="Client", inversedBy="request") 
    * @var Client 
    */ 
    private $client; 

    /** 
    * @ORM\ManyToMany(targetEntity="Status", inversedBy="request") 
    * @ORM\JoinTable(name="request_status") 
    * @var Status 
    */ 
    private $status; 

    /** 
    * @ORM\Column(type="integer") 
    * @var Qualification 
    */ 
    private $qualification; 

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

    /** 
    * @return Salesperson 
    */ 
    public function getSalesperson() 
    { 
     return $this->salesperson; 
    } 

    /** 
    * @param Salesperson $salesperson 
    */ 
    public function setSalesperson($salesperson) 
    { 
     $this->salesperson = $salesperson; 
    } 

    /** 
    * @return Client 
    */ 
    public function getClient() 
    { 
     return $this->client; 
    } 

    /** 
    * @param Client $client 
    */ 
    public function setClient($client) 
    { 
     $this->client = $client; 
    } 

    /** 
    * @return Status 
    */ 
    public function getStatus() 
    { 
     return $this->status; 
    } 

    /** 
    * @param Status $status 
    */ 
    public function setStatus($status) 
    { 
     $this->status = $status; 
    } 

    /** 
    * @return Qualification 
    */ 
    public function getQualification() 
    { 
     return $this->qualification; 
    } 

    /** 
    * @param Qualification $qualification 
    */ 
    public function setQualification($qualification) 
    { 
     $this->qualification = $qualification; 
    } 

    public function __construct($salesperson, $client, $status, $qualification) { 
     $this->salesperson = $salesperson; 
     $this->client = $client; 
     $this->status = $status; 
     $this->qualification = $qualification; 
    } 

} `

Также мой

DAO «RequestBaseDao.php» здесь, который автоматически генерируется.

<?php 

/* 
* This file has been automatically generated by Mouf/ORM. 
* DO NOT edit this file, as it might be overwritten. 
* If you need to perform changes, edit the RequestDao class instead! 
*/ 

namespace EvolisClientRequest\Model\DAOs; 

use Doctrine\ORM\EntityManagerInterface; 
use Doctrine\ORM\EntityRepository; 
use Doctrine\ORM\NonUniqueResultException; 
use Mouf\Doctrine\ORM\Event\SaveListenerInterface; 
use EvolisClientRequest\Model\Entities\Request; 

/** 
* The RequestBaseDao class will maintain the persistence of Request class into the request table. 
* 
* @method Request findByQualification($fieldValue, $orderBy = null, $limit = null, $offset = null) 
* @method Request findOneByQualification($fieldValue, $orderBy = null) 
* @method Request findBySurfaceMin($fieldValue, $orderBy = null, $limit = null, $offset = null) 
* @method Request findOneBySurfaceMin($fieldValue, $orderBy = null) 
* @method Request findBySurfaceMax($fieldValue, $orderBy = null, $limit = null, $offset = null) 
* @method Request findOneBySurfaceMax($fieldValue, $orderBy = null) 
* @method Request findByPriceMin($fieldValue, $orderBy = null, $limit = null, $offset = null) 
* @method Request findOneByPriceMin($fieldValue, $orderBy = null) 
* @method Request findByPriceMax($fieldValue, $orderBy = null, $limit = null, $offset = null) 
* @method Request findOneByPriceMax($fieldValue, $orderBy = null) 
* @method Request findByRequestDate($fieldValue, $orderBy = null, $limit = null, $offset = null) 
* @method Request findOneByRequestDate($fieldValue, $orderBy = null) 

*/ 
class RequestBaseDao extends EntityRepository 
{ 

    /** 
    * @var SaveListenerInterface[] 
    */ 
    private $saveListenerCollection; 

    /** 
    * @param EntityManagerInterface $entityManager 
    * @param SaveListenerInterface[] $saveListenerCollection 
    */ 
    public function __construct(EntityManagerInterface $entityManager, array $saveListenerCollection = []) 
    { 
     parent::__construct($entityManager, $entityManager->getClassMetadata('EvolisClientRequest\Model\Entities\Request')); 
     $this->saveListenerCollection = $saveListenerCollection; 
    } 

    /** 
    * Get a new persistent entity 
    * @param ...$params 
    * @return Request 
    */ 
    public function create(...$params) : Request 
    { 
     $entity = new Request(...$params); 
     $this->getEntityManager()->persist($entity); 
     return $entity; 
    } 

    /** 
    * Peforms a flush on the entity. 
    * 
    * @param Request 
    * @throws \Exception 
    */ 
    public function save(Request $entity) 
    { 
     foreach ($this->saveListenerCollection as $saveListener) { 
      $saveListener->preSave($entity); 
     } 

     $this->getEntityManager()->flush($entity); 

     foreach ($this->saveListenerCollection as $saveListener) { 
      $saveListener->postSave($entity); 
     } 

    } 

    /** 
    * Peforms remove on the entity. 
    * 
    * @param Request $entity 
    */ 
    public function remove(Request $entity) 
    { 
     $this->getEntityManager()->remove($entity); 
    } 

    /** 
    * Finds only one entity. The criteria must contain all the elements needed to find a unique entity. 
    * Throw an exception if more than one entity was found. 
    * 
    * @param array $criteria 
    * 
    * @return Request 
    */ 
    public function findUniqueBy(array $criteria) : Request 
    { 
     $result = $this->findBy($criteria); 

     if (count($result) === 1) { 
      return $result[0]; 
     } elseif (count($result) > 1) { 
      throw new NonUniqueResultException('More than one Request was found'); 
     } else { 
      return; 
     } 
    } 

    /** 
    * Finds only one entity by Qualification. 
    * Throw an exception if more than one entity was found. 
    * 
    * @param mixed $fieldValue the value of the filtered field 
    * 
    * @return Request 
    */ 
    public function findUniqueByQualification($fieldValue) 
    { 
     return $this->findUniqueBy(array('qualification' => $fieldValue)); 
    } 
} 

Мой RequestDao.php, где я могу писать запросы.

<?php 
namespace EvolisClientRequest\Model\DAOs; 
use EvolisClientRequest\Model\Entities\Request; 


/** 
* The RequestDao class will maintain the persistence of Request class into the request table. 
*/ 
class RequestDao extends RequestBaseDao { 

    /*** PUT YOUR SPECIFIC QUERIES HERE !! ***/ 

    public function setdata() 
    { 
     /*$product = new Request(); 
     $product->setStatus('Keyboard'); 
     $product->setClient('000000001ae10dda000000003c4667a6'); 
     $product->setSalesperson('Ergonomic and stylish!'); 
     $product->setQualification('1111'); 
     //var_dump($r);die(); 
     $em = $this->getEntityManager(); 
     $em->persist($product); 
     $em->flush();*/ 
     $product= $this->create('Keyboard','000000001ae10dda000000003c4667a6','Ergonomic and stylish!','1111'); 
     $this->save($product); 

    } 
} 

Наконец мой контроллер "ContactController.php"

<?php 
namespace EvolisClientRequest\Controllers; 

use EvolisClientRequest\Model\DAOs\ClientDao; 
use EvolisClientRequest\Model\Entities\Client; 
use EvolisClientRequest\Model\Entities\Clients; 
use EvolisClientRequest\Model\DAOs\RequestDao; 
use EvolisClientRequest\Model\Entities\Request; 
use EvolisClientRequest\Model\Entities\Requests; 
use EvolisClientRequest\Model\DAOs\SalespersonDao; 
use EvolisClientRequest\Model\Entities\Salesperson; 
use EvolisClientRequest\Model\Entities\Salespersons; 
use Mouf\Mvc\Splash\Annotations\Get; 
use Mouf\Mvc\Splash\Annotations\Post; 
use Mouf\Mvc\Splash\Annotations\Put; 
use Mouf\Mvc\Splash\Annotations\Delete; 
use Mouf\Mvc\Splash\Annotations\URL; 
use Mouf\Html\Template\TemplateInterface; 
use Mouf\Html\HtmlElement\HtmlBlock; 
use Psr\Log\LoggerInterface; 
use \Twig_Environment; 
use Mouf\Html\Renderer\Twig\TwigTemplate; 
use Mouf\Mvc\Splash\HtmlResponse; 
use Doctrine\DBAL\DriverManager; 
use Zend\Diactoros\Response\JsonResponse; 
use Doctrine\Common\Collections\ArrayCollection; 

/** 
* TODO: write controller comment 
*/ 
class ContactController { 

    /** 
    * The logger used by this controller. 
    * @var LoggerInterface 
    */ 
    private $logger; 

    /** 
    * The template used by this controller. 
    * @var TemplateInterface 
    */ 
    private $template; 

    /** 
    * The header of the page. 
    * @var HtmlBlock 
    */ 
    private $header; 


    /** 
    * The main content block of the page. 
    * @var HtmlBlock 
    */ 
    private $content; 

    /** 
    * The Twig environment (used to render Twig templates). 
    * @var Twig_Environment 
    */ 
    private $twig; 


    /** 
    * Controller's constructor. 
    * @param LoggerInterface $logger The logger 
    * @param TemplateInterface $template The template used by this controller 
    * @param HtmlBlock $content The main content block of the page 
    * @param Twig_Environment $twig The Twig environment (used to render Twig templates) 
    */ 
    public function __construct(LoggerInterface $logger, TemplateInterface $template, HtmlBlock $content, HtmlBlock $header, Twig_Environment $twig, ClientDao $clientDao, RequestDao $requestDao, SalespersonDao $salespersonDao) { 
     $this->logger = $logger; 
     $this->template = $template; 
     $this->content = $content; 
     $this->twig = $twig; 
     $this->header = $header; 
     $this->clientDao = $clientDao; 
     $this->requestDao = $requestDao; 
     $this->salespersonDao = $salespersonDao; 
    } 

    /** 
    * @URL("new.html") 

    */ 
    public function new() { 
     // TODO: write content of action here 

     // Let's add the twig file to the template. 
     $this->content->addHtmlElement(new TwigTemplate($this->twig, 'views/contact/new.twig', array("message"=>"world"))); 
     $this->header->addHtmlElement(new TwigTemplate($this->twig, 'views/root/header.twig', array("message"=>"world"))); 
     return new HtmlResponse($this->template); 
    } 

    /** 
    * @URL("saveData") 
    * For Saving the data 
    */ 
    public function saveData() 
    { 
     /*$newClient = $this->clientDao->create('hello', '[email protected]','8907263949'); 
     $this->clientDao->save($newClient);*/ 
     //$data = array(); 
     //$data['salespersonDao']['salesperson'] = '[email protected]'; 
     //$data['request']['qualification'] = 'abcdefgh'; 

     //$newClient = $this->requestDao->create($data); 
     //$newClient = $this->requestDao->setQualification('Keyboard'); 
     // $this->requestDao->save($newClient); 
     $user_data=$this->requestDao->setdata(); 

     //return new JsonResponse([ "status"=>0 ]); 
    } 
} 

Я использую Mouf framework.I я застрял с этим problem.Someone Пожалуйста, помогите мне решить эту проблему. Заранее спасибо

+0

В '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' должны быть массивом, но вы назначаете их как строки. Попробуйте использовать этот пример: '$ this-> salesperson [] = $ salesperson;' и т. Д. С 'status' – rokas

+0

Я этого не понял .. вы можете сделать это ясно. – sarathChandran

+0

' ManyToMany' и 'OneToMany' отношения всегда массивы коллекций, поэтому переменные должны быть массивами (например: http://pastebin.com/EsJNGMrk) – rokas

ответ

1

Как вам советует @rokas, вы действительно должны начать читать больше о доктрине. Это не проблема Mouf, это явно проблема Doctrine ORM поэтому соответствующий документ здесь: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/index.html

Вот несколько советов:

Ваш контроллер вызывает setdata метод

$user_data=$this->requestDao->setdata(); 

setdata метод вызывает:

$product= $this->create('Keyboard','000000001ae10dda000000003c4667a6','Ergonomic and stylish!','1111'); 

Теперь метод create является:

public function create(...$params) : Request 
{ 
    $entity = new Request(...$params); 
    $this->getEntityManager()->persist($entity); 
    return $entity; 
} 

Это означает, что он будет вызывать Request конструктор с этим параметрами:

$entity = new Request('Keyboard','000000001ae10dda000000003c4667a6','Ergonomic and stylish!','1111'); 

Посмотрите на Request конструктору:

public function __construct($salesperson, $client, $status, $qualification) { 
    $this->salesperson = $salesperson; 
    $this->client = $client; 
    $this->status = $status; 
    $this->qualification = $qualification; 
} 

Как вы можете видеть, первый параметр есть $salesperson. Вы пытаетесь поместить значение «Клавиатура» здесь. Атрибут $salesperson определяется следующим образом:

/** 
* @ORM\ManyToMany(targetEntity="Salesperson", inversedBy="request") 
* @ORM\JoinTable(name="request_salesperson") 
* @var Salesperson 
*/ 
private $salesperson; 

/** 
* @param Salesperson $salesperson 
*/ 
public function setSalesperson($salesperson) 
{ 
    $this->salesperson = $salesperson; 
} 

Теперь, вот ваша проблема, я думаю.

Недвижимость $salesperson определяется как ассоциация «ManyToMany». Таким образом, вы действительно не можете поставить строку здесь, это коллекция Salesperson. Кстати, вы тоже не должны «устанавливать» что-либо. Установщик должен быть полностью удален.

Вместо этого, вы должны рассмотреть возможность использования его в соответствии с документацией здесь: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/working-with-associations.html

Например:

$request->getSalesPersons()->add($someObjectRepresentingAPerson); 

Кроме того, обратите внимание, что поскольку $salesperson представляет коллекцию объекта SALESPERSON, Вам необходимо сделать на самом деле это имя $salesPersons (множественное число)

+0

Спасибо. Вы сохранили мою неделю – sarathChandran

Смежные вопросы