Doctrine2 dont want to insert the columns in the table - php

Here is my Insert Query, how can I tell that, created_at(current time-stamp), is_active(default 1) set in the mysql db structure needs to be taken.
When I omit the $question->setCreatedAt($this->createdAt); in the insert operation it shows me an Integrity constraint violation, do you know what is the issue?
In the Questions table:
question:
id
question
created_by
created_at
modified_by
modified_at
is_Active
Entity:
<?php
namespace Library\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Base class for all the Entities
* This class maps id, active, created and modified columns
*
* #author
*/
/**
* #ORM\MappedSuperclass
*/
class BaseEntity {
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(name="id", type="integer")
* #var integer
*/
protected $id;
/**
* #ORM\Column(name="is_active", type="boolean")
* #var boolean
*/
protected $active;
/**
* #ORM\Column(name="created_at", type="datetime")
* #var datetime
*/
protected $createdAt;
/**
* #ORM\Column(name="created_by", type="integer", nullable=true)
* #var integer
*/
protected $createdBy;
/**
* #ORM\Column(name="modified_at", type="datetime")
* #var datetime
*/
protected $modifiedAt;
/**
* #ORM\Column(name="modified_by", type="integer")
* #var integer
*/
protected $modifiedBy;
public function getId() {
return $this->id;
}
public function getActive() {
return $this->active;
}
public function getCreatedAt() {
return $this->createdAt;
}
public function getCreatedBy() {
return $this->createdBy;
}
public function getModifiedAt() {
return $this->modifiedAt;
}
public function getModifiedBy() {
return $this->modifiedBy;
}
public function setId($id) {
$this->id = $id;
}
public function setActive($active) {
$this->active = $active;
}
public function setCreatedAt($createdAt) {
$this->createdAt = $createdAt;
}
public function setCreatedBy($createdBy) {
$this->createdBy = $createdBy;
}
public function setModifiedAt($modifiedAt) {
$this->modifiedAt = $modifiedAt;
}
public function setModifiedBy($modifiedBy) {
$this->modifiedBy = $modifiedBy;
}
}
This is my Question Entity:
<?php
namespace Survey\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Library\Entity\BaseEntity;
use Survey\Entity\Survey;
/**
* Description of Survey Questions
*
* #author Mubarak
*/
/**
* #ORM\Entity
* #ORM\Table(name="survey_questions")
*/
class Question extends BaseEntity{
/**
* #ORM\Column(name="question", type="string")
* #var string
*/
protected $question;
/**
* #ORM\ManyToOne(targetEntity="Survey\Entity\Survey", inversedBy="questions")
* #ORM\JoinColumn(name="survey_id", referencedColumnName="id")
*/
private $surveys;
public function getQuestion() {
return $this->question;
}
public function setQuestion($question) {
$this->question = $question;
}
public function getSurveys() {
return $this->surveys;
}
// public function setSurveys(ArrayCollection $survey) {
public function setSurveys(Survey $surveys = null) {
$this->surveys = $surveys;
}
// public function __toString() {
// return __CLASS__ . ": [id: {$this->id}, name: {$this->name}]";
// }
}
Here is my insert Operation:
public function insertQuestion($userId, $survey, $questionArr) {
try{
$question = new Question();
$question->setQuestion($questionArr['question']);
$question->setSurveys($survey);
$question->setActive(1);
$question->setCreatedBy($userId);
$question->setCreatedAt($this->createdAt);
$question->setModifiedBy($userId);
$question->setModifiedAt($this->modifiedAt);
$this->entityManager->persist($question);
$this->entityManager->flush();
return $question;
}catch(Exception $ex){
throw new Exception("Couldnt insert the question");
}
}
This is Ok, its working properly, but i dont want to insert the Created_at, modified_at
public function insertQuestion($userId, $survey, $questionArr) {
try{
$question = new Question();
$question->setQuestion($questionArr['question']);
$question->setSurveys($survey);
$question->setActive(1);
$question->setCreatedBy($userId);
$question->setModifiedBy($userId);
$this->entityManager->persist($question);
$this->entityManager->flush();
return $question;
}catch(Exception $ex){
throw new Exception("Couldnt insert the question");
}
}

If you want to set default values it is best to set them in your object model where possible.
/**
* #ORM\Column(name="is_active", type="boolean")
* #var boolean
*/
protected $active = true;
For time-stamps though it is a bit of a different story...
I would suggest to take a look at the Gedmo doctrine extensions library which includes solutions for createdAt and other common columns for your model. No need to reinvent the wheel... .

Related

SQLSTATE[42S22]: Column not found: 1054 Unknown column in 'field list' while trying to sort entities

I am trying to implement sorting in my Symfony 6 project.
Here is the entity I am trying to sort :
<?php
namespace App\Entity;
use App\Entity\Workflow\Status;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use App\Entity\Plant;
use App\Entity\DetailedCause;
/**
* #ORM\Entity(repositoryClass=\App\Repository\RequestRepository::class)
*/
class Request
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string")
*/
private $requesterName;
/**
* #ORM\Column(type="string")
*/
private $requesterService;
/**
* #ORM\Column(type="string")
*/
private $requesterMatricule;
/**
* #ORM\Column(type="integer")
*/
private $priority;
/**
* #ORM\Column(type="integer")
*/
private $type;
/**
* #ORM\Column(type="boolean")
*/
private $flagSupp;
/**
* #ORM\Column(type="integer", nullable=true)
*/
private $estimatedLoad;
/**
* #ORM\Column(type="text")
*/
private $reason;
/**
* #ORM\Column(type="datetime", nullable=false)
*/
private $date;
/**
* #ORM\ManyToOne(targetEntity=Workflow\Status::class)
* #ORM\JoinColumn(nullable=false)
*/
private Status $state;
/**
* #ORM\Column(type="string", length=50, nullable=true)
*/
private $product;
/**
* #ORM\Column(type="string", length=50, nullable=true)
*/
private $program;
/**
* #ORM\ManyToOne(targetEntity=DetailedCause::class)
* #ORM\JoinColumn(nullable=false)
*/
private DetailedCause $detailedCause;
/**
* #ORM\ManyToOne(targetEntity=Cause::class)
*/
private $cause;
/**
* #ORM\ManyToOne(targetEntity=Plant::class)
* #ORM\JoinColumn(nullable=false)
*/
private Plant $impactedPlant;
/**
* #ORM\OneToMany(targetEntity=Action::class, mappedBy="request")
*/
private $actions;
/**
* #ORM\ManyToOne(targetEntity=Plant::class)
* #ORM\JoinColumn(nullable=false)
*/
private Plant $requesterPlant;
public function __construct()
{
$this->actions = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getRequesterPlant(): ?Plant
{
return $this->requesterPlant;
}
public function setRequesterPlant(?Plant $requesterPlant): self
{
$this->requesterPlant = $requesterPlant;
return $this;
}
//the rest of getters and setters
}
and the repository :
<?php
namespace App\Repository;
use App\Entity\Request;
use App\Entity\RequestFilter;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\ORM\Tools\Pagination\Paginator;
use Doctrine\Persistence\ManagerRegistry;
use App\Entity\Plant;
/**
* #method Request|null find($id, $lockMode = null, $lockVersion = null)
* #method Request|null findOneBy(array $criteria, array $orderBy = null)
* #method Request[] findAll()
* #method Request[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
* #method Paginator getRequestPaginator(int $offset = 0, string $order = 'id')
*/
class RequestRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Request::class);
}
/**
* #var int $offset
* #param RequestFilter
* #return Paginator Returns a paginator of requests using filters
*/
public function getRequestPaginator($offset = 0, RequestFilter $filter = null)
{
if ($filter == null) {
$filter = new RequestFilter();
}
#adds filter parameters to the query
$query = $this->createQueryBuilder('r');
if ($filter->getStates() != null){
$query
->andWhere('r.state IN (:states)')
->setParameter('states', $filter->getStates());//;
}
#adds the rest of the params
$query = $query
//this orderBy clause is triggering the error
->orderBy('r.' . $filter->getOrder(), $filter->getOrderDirection())
->setFirstResult($offset)
->setMaxResults($filter->getRequestsPerPage())
->getQuery();
return new Paginator($query);
}
}
this works fine for most attributes. I can sort by date, requester name, etc.
But when I try to sort by requesterPlant, which is a doctrine Entity, I get the following error :
("An exception occurred while executing a query: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'r0_.requester_plant_id' in 'field list'").
This column does exist in the database just like other columns. I do not understand why doctrine is stuck on this. Migrations are up to date, I've cleared cache, and I've been stuck on this problem for days.
I would really appreciate if anyone had a clue about what is happening there.
As additional info, here is my Plant entity :
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass=\App\Repository\PlantRepository::class)
*/
class Plant
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
* #ORM\OneToMany(targetEntity="App\Entity\Request", mappedBy="requesterPlant")
*/
private int $id;
/**
* #ORM\Column(type="string", length=255)
*/
private string $designation;
/**
* #ORM\Column(type="string", length=50)
*/
private string $plantString;
/**
* #ORM\Column(type="string", length=50)
*/
private string $company;
public function getId(): ?int
{
return $this->id;
}
public function setID(int $id): self
{
$this->id = $id;
return $this;
}
public function getDesignation(): ?string
{
return $this->designation;
}
public function setDesignation(string $designation): self
{
$this->designation = $designation;
return $this;
}
public function getPlantString(): ?string
{
return $this->plantString;
}
public function setPLantString(string $plantString): self
{
$this->plantString = $plantString;
return $this;
}
public function getCompany(): ?string
{
return $this->company;
}
public function setCompany(string $company): self
{
$this->company = $company;
return $this;
}
}

Doctrine2 entity , tell not update certain columns

I don't want to update certain columns for the table.
In the Questions table, I just want to update the question column:
question:
id
question
created_by
created_at
modified_by
modified_at
is_Active
In the above table column, I don't need to update the create_at, created_by, modified_by, modified_at, is_active columns. This is the entity I am using.
Entity:
<?php
namespace Library\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Base class for all the Entities
* This class maps id, active, created and modified columns
*
* #author
*/
/**
* #ORM\MappedSuperclass
*/
class BaseEntity {
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(name="id", type="integer")
* #var integer
*/
protected $id;
/**
* #ORM\Column(name="is_active", type="boolean")
* #var boolean
*/
protected $active;
/**
* #ORM\Column(name="created_at", type="datetime")
* #var datetime
*/
protected $createdAt;
/**
* #ORM\Column(name="created_by", type="integer", nullable=true)
* #var integer
*/
protected $createdBy;
/**
* #ORM\Column(name="modified_at", type="datetime")
* #var datetime
*/
protected $modifiedAt;
/**
* #ORM\Column(name="modified_by", type="integer")
* #var integer
*/
protected $modifiedBy;
public function getId() {
return $this->id;
}
public function getActive() {
return $this->active;
}
public function getCreatedAt() {
return $this->createdAt;
}
public function getCreatedBy() {
return $this->createdBy;
}
public function getModifiedAt() {
return $this->modifiedAt;
}
public function getModifiedBy() {
return $this->modifiedBy;
}
public function setId($id) {
$this->id = $id;
}
public function setActive($active) {
$this->active = $active;
}
public function setCreatedAt($createdAt) {
$this->createdAt = $createdAt;
}
public function setCreatedBy($createdBy) {
$this->createdBy = $createdBy;
}
public function setModifiedAt($modifiedAt) {
$this->modifiedAt = $modifiedAt;
}
public function setModifiedBy($modifiedBy) {
$this->modifiedBy = $modifiedBy;
}
}
This is my Question Entity:
<?php
namespace Survey\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Library\Entity\BaseEntity;
use Survey\Entity\Survey;
/**
* Description of Survey Questions
*
* #author Mubarak
*/
/**
* #ORM\Entity
* #ORM\Table(name="survey_questions")
*/
class Question extends BaseEntity{
/**
* #ORM\Column(name="question", type="string")
* #var string
*/
protected $question;
/**
* #ORM\ManyToOne(targetEntity="Survey\Entity\Survey", inversedBy="questions")
* #ORM\JoinColumn(name="survey_id", referencedColumnName="id")
*/
private $surveys;
public function getQuestion() {
return $this->question;
}
public function setQuestion($question) {
$this->question = $question;
}
public function getSurveys() {
return $this->surveys;
}
// public function setSurveys(ArrayCollection $survey) {
public function setSurveys(Survey $surveys = null) {
$this->surveys = $surveys;
}
// public function __toString() {
// return __CLASS__ . ": [id: {$this->id}, name: {$this->name}]";
// }
}
Here is my update function:
public function updateQuestion($userId, $data ) {
try{
$surveyId = 1;
$survey = $this->entityManager->getRepository('Survey\Entity\Survey')->find($surveyId);
$question = new Question();
$question->setQuestion($data['question']);
$question->setSurveys($survey);
$question->setId(1);
$this->entityManager->merge($question);
$this->entityManager->flush();
} catch (Exception $ex) {
throw new Exception("Couldnt update the Question");
}
Below is my error message i am getting:
An exception occurred while executing 'UPDATE survey_questions SET is_active = ?, created_at = ?, created_by = ?, modified_at = ?, modified_by = ? WHERE id = ?' with params [null, null, null, null, null, 1]:\n\nSQLSTATE[23000]: Integrity constraint violation: 1048 Column 'created_at' cannot be null
Here is my insert Operation:
public function insertQuestion($userId, $survey, $questionArr) {
try{
$question = new Question();
$question->setQuestion($questionArr['question']);
$question->setSurveys($survey);
$question->setActive(1);
$question->setCreatedBy($userId);
$question->setCreatedAt($this->createdAt);
$question->setModifiedBy($userId);
$question->setModifiedAt($this->modifiedAt);
$this->entityManager->persist($question);
$this->entityManager->flush();
return $question;
}catch(Exception $ex){
throw new Exception("Couldnt insert the question");
}
}
The problem is that you are creating a new entity, Question.
When calling EntityManager::flush() Doctrine computes the changesets of all the currently managed entities and saves the differences to the database. In case of object properties (#Column(type=”datetime”) or #Column(type=”object”)) these comparisons are always made BY REFERENCE.
"By reference" is important because your new entity has null values for all date time fields (rather than the previously set \DateTime instances). When flush() is called Doctrine correctly detects that these fields are changed and performs the query which fails at the database level.
The merge() operation isn't required in Doctrine when 'editing' entities, these are used for detached instances that need to be managed again.
To solve this you should load the managed instance of the entity first; then modify the fields and flush.
$question = $entityManager->find(1);
$question->setQuestion($data['question']);
$entityManager->flush();

Mapping FAIL - The entity-class 'PI\UnidadBundle\Entity\HorasPorUnidad' mapping is invalid

I'm having a problem here and I don't know how to fix it. See I have this two entities:
<?php
namespace PI\ProyectoBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\Event\LifecycleEventArgs;
/**
* #ORM\Entity
* #ORM\Table(name="proyectos")
* #ORM\Entity(repositoryClass="PI\ProyectoBundle\Entity\Repository\ProyectosRepository")
* #ORM\HasLifecycleCallbacks
*/
class Proyectos {
/**
* #ORM\Id
* #ORM\Column(type="integer")
*/
protected $id;
/**
* #ORM\Column(type="string", length=45, unique=true, nullable=false)
*/
protected $nombre;
/**
* #ORM\Column(type="boolean", nullable=true)
*/
protected $estado;
/**
* #ORM\Column(type="string", length=45, nullable=false)
*/
protected $pais;
/**
* #ORM\Id
* #ORM\ManyToOne(targetEntity="PI\ClienteBundle\Entity\Clientes", cascade={"all"})
* #ORM\JoinColumn(name="cliente", referencedColumnName="id")
*/
protected $clientes;
/**
* #ORM\ManyToMany(targetEntity="PI\CentroBundle\Entity\Centros", inversedBy="proyectos", cascade={"persist"})
* #ORM\JoinTable(name="proyectos_has_centros",
* joinColumns={#ORM\JoinColumn(name="proyectos_id", referencedColumnName="id"),
* #ORM\JoinColumn(name="proyectos_cliente", referencedColumnName="cliente")},
* inverseJoinColumns={#ORM\JoinColumn(name="centros_id", referencedColumnName="id")}
* )
*/
protected $centros;
/**
* #ORM\ManyToMany(targetEntity="Application\Sonata\UserBundle\Entity\User", cascade={"persist"})
* #ORM\JoinTable(name="proyectos_has_system_user",
* joinColumns={#ORM\JoinColumn(name="proyectos_id", referencedColumnName="id"),
* #ORM\JoinColumn(name="proyectos_cliente", referencedColumnName="cliente")},
* inverseJoinColumns={#ORM\JoinColumn(name="system_user_id", referencedColumnName="id")}
* )
*/
protected $ingenieros;
public function __construct() {
$this->centros = new \Doctrine\Common\Collections\ArrayCollection();
$this->ingenieros = new \Doctrine\Common\Collections\ArrayCollection();
}
public function getId() {
return $this->id;
}
public function setNombre($nombre) {
$this->nombre = $nombre;
}
public function getNombre() {
return $this->nombre;
}
public function setEstado($estado) {
$this->estado = $estado;
}
public function getEstado() {
return $this->estado;
}
public function setPais($pais) {
$this->pais = $pais;
}
public function getPais() {
return $this->pais;
}
public function setClientes(\PI\ClienteBundle\Entity\Clientes $clientes) {
$this->clientes = $clientes;
}
public function getClientes() {
return $this->clientes;
}
public function setCentros(\PI\CentroBundle\Entity\Centros $centros) {
$this->centros[] = $centros;
}
public function getCentros() {
return $this->centros;
}
public function setIngenieros(\BIT\UserBundle\Entity\User $ingenieros) {
$this->ingenieros[] = $ingenieros;
}
public function getIngenieros() {
return $this->ingenieros;
}
/**
* #ORM\PrePersist
*/
public function prePersist(LifecycleEventArgs $eventArgs) {
$em = $eventArgs->getEntityManager();
$q = $em->createQuery('SELECT MAX(p.id) FROM PIProyectoBundle:Proyectos p');
$id = $q->getSingleResult(\Doctrine\ORM\Query::HYDRATE_SINGLE_SCALAR);
$this->id = $id + 1;
}
}
And this other:
<?php
namespace PI\UnidadBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="horas_por_proyectos")
*/
class HorasPorUnidad {
/**
* #ORM\Id
* #ORM\ManyToOne(targetEntity="Application\Sonata\UserBundle\Entity\User", cascade={"all"})
* #ORM\JoinColumn(name="fos_user_user_id", referencedColumnName="id")
*/
protected $fos_user_user_id;
/**
* #ORM\Id
* #ORM\ManyToOne(targetEntity="PI\UnidadBundle\Entity\Unidades", cascade={"all"})
* #ORM\JoinColumn(name="fos_user_user_id", referencedColumnName="id")
*/
protected $unidades_id;
/**
* #ORM\Id
* #ORM\ManyToOne(targetEntity="PI\CentroBundle\Entity\Centros", cascade={"all"})
* #ORM\JoinColumn(name="centros_id", referencedColumnName="id")
*/
protected $centros_id;
/**
* #ORM\Id
* #ORM\ManyToOne(targetEntity="PI\ProyectoBundle\Entity\Proyectos", cascade={"all"})
* #ORM\JoinColumn(name="proyectos_id", referencedColumnName="id")
*/
protected $proyectos_id;
/**
* #ORM\Id
* #ORM\ManyToOne(targetEntity="PI\ClienteBundle\Entity\Clientes", cascade={"all"})
* #ORM\JoinColumn(name="proyectos_cliente", referencedColumnName="id")
*/
protected $proyectos_cliente;
/**
* #ORM\Column(type="date")
*/
protected $fecha;
/**
* #ORM\Column(type="integer")
*/
protected $horas;
public function setUserId(\Application\Sonata\UserBundle\Entity\User $user) {
$this->fos_user_user_id = $user;
}
public function getUserId() {
return $this->fos_user_user_id;
}
public function setUnidadesId(\PI\UnidadBundle\Entity\Unidades $unidad) {
$this->unidades_id = $unidad;
}
public function getUnidadesId() {
return $this->unidades_id;
}
public function setCentrosId(\PI\CentroBundle\Entity\Centros $centro) {
$this->centros_id = $centro;
}
public function getCentrosId() {
return $this->centros_id;
}
public function setHoras($cantidad_horas) {
$this->horas = $cantidad_horas;
}
public function getHoras() {
return $this->horas;
}
public function setFecha($fecha) {
$this->fecha = $fecha;
}
public function getFecha() {
return $this->fecha;
}
}
But when I run the task php app/console doctrine:schema:validate I get this errors:
[Mapping] FAIL - The entity-class 'PI\UnidadBundle\Entity\HorasPorUnidad' mapping is invalid:
Cannot map association 'PI\UnidadBundle\Entity\HorasPorUnidad#proyectos_id as identifier, because the target entity 'PI\ProyectoBundle\Entity\Proyectos' also maps an association as identifier.
The join columns of the association 'proyectos_id' have to match to ALL identifier columns of the target entity 'PI\UnidadBundle\Entity\HorasPorUnidad', however 'id, cliente' are missing.
And I don't know how to fix them, so any help from experts? What I need to fix here?
You foget the mappedBy and inversedBy attributes in the ManyToOne assocciation and also check the other side of your assocciations:
/**
* #ORM\Id
* #ORM\ManyToOne(targetEntity="PI\ClienteBundle\Entity\Clientes",inversedBy="?" cascade={"all"})
* #ORM\JoinColumn(name="cliente", referencedColumnName="id")
*/
protected $clientes;

Symfony2 Entity doctrine2 don't update field

I have this entity:
Profile.php
/**
* LoPati\BlogBundle\Entity\Profile
*
* #ORM\Table(name="profile")
* #ORM\Entity
* #Gedmo\TranslationEntity(class="LoPati\BlogBundle\Entity\ProfileTranslation")
*/
class Profile
{
/**
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #Gedmo\Translatable
* #ORM\Column(name="name", type="string", length=255, nullable=true)
*/
protected $name=null;
/**
* #var text $description
* #Gedmo\Translatable
* #ORM\Column(name="description", type="text", nullable=true)
*/
protected $description=null;
/**
* #ORM\OneToMany(targetEntity="ProfileTranslation", mappedBy="object", cascade={"persist", "remove"})
*/
protected $translations;
/**
* Required for Translatable behaviour
* #Gedmo\Locale
*/
protected $locale;
public function __construct()
{
$this->translations = new ArrayCollection;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
public function getLocale()
{
return $this->locale;
}
public function setLocale($locale)
{
$this->locale = $locale;
}
public function setName($name)
{
$this->name=$name;
}
public function getName()
{
return $this->name;
}
public function setDescription($description)
{
}
public function getDescription()
{
return $this->description;
}
public function getTranslations()
{
return $this->translations;
}
public function addTranslation(ProfileTranslation $t)
{
$this->translations->add($t);
$t->setObject($this);
$this->name = $this->translations[0];
$this->description = $this->translations[1];
}
public function removeTranslation(ProfileTranslation $t)
{
$this->translations->removeElement($t);
}
public function setTranslations($translations)
{
$this->translations = $translations;
$this->name = $this->translations[0];
$this->description = $this->translations[1];
}
public function __toString()
{
return "hola";
}
}
And ProfileTranslation.php
/**
* #ORM\Entity
* #ORM\Table(name="profile_translations",
* uniqueConstraints={#ORM\UniqueConstraint(name="lookup_unique_idx", columns={
* "locale", "object_id", "field"
* })}
* )
*/
class ProfileTranslation extends AbstractPersonalTranslation
{
/**
* Convinient constructor
*
* #param string $locale
* #param string $field
* #param string $content
*/
public function __construct($locale = null, $field = null, $content = null)
{
$this->setLocale($locale);
$this->setField($field);
$this->setContent($content);
}
/**
* #ORM\ManyToOne(targetEntity="Profile", inversedBy="translations")
* #ORM\JoinColumn(name="object_id", referencedColumnName="id", onDelete="CASCADE")
*/
protected $object;
public function __toString()
{
return $this->getContent();
}
}
I want that when edit arraycollection that is a ProfileTranslation table, then also update the name and description field but form Profile Table, and it be the first element that collection.
It work when I create new Profile, but when I edit this profile, only update the ProfileTranslation Table and not Profile table.
How I can do it?
Your implementation turns away a little too classic Translatable use.
You could maybe have a look about TranslationFormBundle and its Demo if it right for you.

Doctrine 2 Model One-to-Many Many-to-One Queries

I have such doctrine entities:
<?php
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #Entity(repositoryClass="App\Repository\Page")
* #Table(name="page")
*/
class Page
{
/**
* #Id #Column(type="integer", name="p_id")
* #GeneratedValue
*/
private $p_id;
/** #Column(type="string", name="p_title") */
private $p_title;
/** #Column(type="datetime", name="p_created") */
private $p_created_at;
/** #Column(type="datetime", name="p_updated_at") */
private $p_updated_at;
/** #Column(type="text", name="p_abstract") */
private $p_abstract;
/** #Column(type="text", name="p_fulltext", nullable=false) */
private $p_fulltext;
/** #Column(type="string", name="p_author", nullable=true) */
private $p_author;
/** #Column(type="string", name="p_url",nullable=true) */
private $p_url;
/** #Column(type="string", name="p_meta_title",nullable=true) */
private $p_meta_title;
/** #Column(type="string", name="p_meta_keywords",nullable=true) */
private $p_meta_keywords;
/** #Column(type="string", name="p_meta_description",nullable=true) */
private $p_meta_description;
/** #Column(type="string", name="p_status") */
private $p_status;
/**
* #ManyToOne(targetEntity="User", inversedBy="pages")
* #JoinColumn(name="p_u_id", referencedColumnName="u_id")
*/
private $user;
/**
* #OneToMany(targetEntity="App\Entity\Page\Media", mappedBy="pages")
* #var \Doctrine\Common\Collections\Collection
*/
protected $pageMedia;
/**
* #OneToMany(targetEntity="App\Entity\Page\Basket", mappedBy="baskets")
* #var \Doctrine\Common\Collections\Collection
*/
protected $pageBasket;
public function __construct()
{
$this->pageMedia = new App\Entity\Page\Media();
$this->medias = new ArrayCollection();
}
public function __get($property)
{
return $this->property;
}
public function __set($property,$value)
{
$this->$property = $value;
}
public function setUser(user $user)
{
$this->user = $user;
}
public function setMedia(media $media)
{
$this->pageMedia->setPageAndMedia($this,$media);
}
/**
* Set Page Values
* #var array $values
*/
public function setPageProperties(array $values)
{
$this->p_updated_at = new \DateTime("now");
$this->p_title = $values['p_title'];
$this->p_abstract = $values['p_abstract'];
$this->p_meta_title = $values['p_meta_title'];
$this->p_meta_keywords = $values['p_meta_keywords'];
$this->p_meta_description = $values['p_meta_description'];
$this->p_url = $values['p_url'];
$this->p_fulltext = $values['p_abstract'];
$this->p_author = '';
$this->p_status = 1;
}
}
?>
<?php
namespace App\Entity\Page;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #Entity
* #Table(name="page_basket")
*/
class Basket
{
/**
* #Id #Column(type="integer", name="pb_id")
* #GeneratedValue
*/
private $pb_id;
/**
* #ManyToOne(targetEntity="App\Entity\Page")
* #JoinColumn(name="pb_p_id", referencedColumnName="p_id")
*/
private $pages;
/**
* #ManyToOne(targetEntity="App\Entity\Basket",inversedBy="pageBasket")
* #JoinColumn(name="pb_b_id", referencedColumnName="b_id")
*/
private $baskets;
public function __construct()
{
$this->baskets = new ArrayCollection();
$this->pages = new ArrayCollection();
}
public function __get($property)
{
return $this->property;
}
public function __set($property,$value)
{
$this->$property = $value;
}
/**
*
*/
public function setPageAnBasket(page $page,basket $basket)
{
$this->pages[] = $page;
$this->baskets[] = $basket;
}
}
?>
And method in repository:
<?php
namespace App\Repository;
use Doctrine\ORM\EntityRepository;
class Page extends EntityRepository
{
/**
* Find pages by basket Id
* #var int $basketId
* #return array $pages[]
*/
public function findPagesByBasket($basketId)
{
$dql = $this->_em->createQueryBuilder();
$dql->select('u')
->from('App\Entity\Page', 'p')
->leftJoin('p.App\Entity\Page\Basket','pb_b_id = p_id')
->andWhere('pb_b_id = :basketId')
->setParameter('basketId', $basketId);
return $dql->getQuery()->getArrayResult();
}
}
But when I ry to run dql all I'm getting:
string '[Semantical Error] line 0, col 67 near 'pb_b_id = p_id': Error: Class App\Entity\Page has no association named App\Entity\Page\Basket'
What I'm doing wrong because I don't want to use many to many relation because I wanna have additional fields in join table.
I needed a good excuse to make myself a simple test case so here it is.
namespace Entity;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #Entity()
* #Table(name="page")
*/
class Page
{
/**
* #Id #Column(type="integer", name="p_id")
* #GeneratedValue
*/
private $id;
/**
* #OneToMany(targetEntity="Entity\PageBasket", mappedBy="page")
*/
protected $pageBaskets;
public function __construct()
{
$this->pageBaskets = new ArrayCollection();
}
public function getId() { return $this->id; }
public function getPageBaskets() { return $this->pageBaskets; }
}
namespace Entity;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #Entity
* #Table(name="page_basket")
*/
class PageBasket
{
/**
* #Id #Column(type="integer", name="pb_id")
* #GeneratedValue
*/
private $id;
/**
* #ManyToOne(targetEntity="Entity\Page")
* #JoinColumn(name="page_id", referencedColumnName="p_id")
*/
private $page;
public function setPage($page)
{
$this->page = $page;
}
public function getId() { return $this->id; }
}
And a working test query
protected function testQuery()
{
$basketId = 1;
$em = $this->getEntityManager();
$qb = $em->createQueryBuilder();
$qb->addSelect('page');
$qb->addSelect('pageBasket');
$qb->from('\Entity\Page','page');
$qb->leftJoin('page.pageBaskets','pageBasket');
$qb->andWhere($qb->expr()->in('pageBasket.id',$basketId));
$query = $qb->getQuery();
$results = $query->getResult();
$page = $results[0];
$pageBaskets = $page->getPageBaskets();
$pageBasket = $pageBaskets[0];
echo 'Result Count ' . count($results) . "\n";
echo 'Page ID ' . $page->getId() . "\n";
echo 'Page Basket ID ' . $pageBasket->getId() . "\n";
echo $query->getSQL() . "\n";
}
The generated sql look like:
SELECT p0_.p_id AS p_id0, p1_.pb_id AS pb_id1, p1_.page_id AS page_id2
FROM page p0_
LEFT JOIN page_basket p1_ ON p0_.p_id = p1_.page_id
WHERE p1_.pb_id IN (1)

Categories