Doctrine2 Inheritance Mapping - Wrong ID used - entity-framework

i'm havin a little problem at the moment.
There's an parent Entity Comment with CommentType and CommentId and some other fields.
Also there are some differently CommentEntites (like CommentText or CommentPhoto) which extends the parent Entity.
The expected behaviour should be, that Doctrine loads Data with ContentId from Entity CommentText or CommentImage (depending on CommentType).
But at the moment it's loaded with the ID from the Parent Entity.
The Parent Entity:
use Doctrine\ORM\Mapping as ORM;
/**
* Comment
*
* #ORM\Table(name="comments")
* #ORM\Entity
* #ORM\InheritanceType("JOINED")
* #ORM\DiscriminatorColumn(name="comment_type", type="string")
* #ORM\DiscriminatorMap( {"txt" = "CommentTxt", "img" = "CommentImg"} )
*/
abstract class Comment
{
/**
* #var integer
*
* #ORM\Column(name="content_id", type="integer", nullable=true)
*/
private $contentId;
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
//and so on
One of the Children Entities:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* CommentTxt
*
* #ORM\Table(name="comment_text")
* #ORM\Entity
*/
class CommentText extends Comment
{
/**
* #var string
*
* #ORM\Column(name="content", type="text", length=65535, nullable=false)
*/
private $content;
/**
* #var \DateTime
*
* #ORM\Column(name="created_at", type="datetime", nullable=false)
*/
private $createdAt;
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
//and some more
How can i change this behaviour?
Greets

Related

doctrine ManyToOne relation crashes symfony 3.3.1

We have an old postgres 9.2 database with more than 400 tables. I used the symfony console to generate the entities, I created the repository classes that I need myself.
When I remove all relations from an entity, build a controller and repository to fetch some objects, everything works fine. But when I add a ManyToOne relation again symfony loads for about a minute or two and then I get a chrome error page "ERR_CONNECTION_REFUSED". Maybe someone can help.
AppBundle\Entity\Firma.php (shortened for better visibility)
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Firma
*
* #ORM\Table(name="firma", uniqueConstraints={#ORM\UniqueConstraint(name="firma_fid_key", columns={"fid"})}, indexes={#ORM\Index(name="IDX_2BED3563DF1BF902", columns={"ftypid"}), #ORM\Index(name="IDX_2BED35632453407B", columns={"hstraegerid"}), #ORM\Index(name="IDX_2BED356318F71675", columns={"hstypid"}), #ORM\Index(name="IDX_2BED3563950F9D92", columns={"uniid"})})
* #ORM\Entity(repositoryClass="AppBundle\Repository\FirmaRepository")
*/
class Firma
{
/**
* #var integer
*
* #ORM\Column(name="fid", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="SEQUENCE")
* #ORM\SequenceGenerator(sequenceName="firma_fid_seq", allocationSize=1, initialValue=1)
*/
private $fid;
/**
* #var \AppBundle\Entity\Ftyp
*
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Ftyp")
* #ORM\JoinColumn(name="ftypid", referencedColumnName="ftypid")
*/
private $ftypid;
AppBundle\Repository\FirmaRepository.php
namespace AppBundle\Repository;
use Doctrine\ORM\EntityRepository;
class FirmaRepository extends EntityRepository
{
}
AppBundle\Entity\Ftyp.php (shortened for visibility)
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Ftyp
*
* #ORM\Table(name="ftyp")
* #ORM\Entity(repositoryClass="AppBundle\Repository\FtypRepository")
*/
class Ftyp
{
/**
* #var integer
*
* #ORM\Column(name="ftypid", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="SEQUENCE")
* #ORM\SequenceGenerator(sequenceName="ftyp_ftypid_seq", allocationSize=1, initialValue=1)
*/
private $ftypid;
/**
* #var string
*
* #ORM\Column(name="ftyp", type="string", length=64, nullable=false)
*/
private $ftyp;
}

Specific form with two enities with Symfony

I have a Category entity, this entity allow me to create a tree of my data :
I would like to create a DiscountGrid entity. A DiscountGrid is composed by a textfield name, and an array containing the discount percentage by category ($discount[idCategory] = $percentage).
In fact, I would like a form like this :
The output would be $discount[ 1 ] = 25, $discount[ 2 ] = 30,.....
I have no idea how handle this behavior with Symfony framework. Here is the declaration of my entities
class Category{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="slug", type="string", length=255, nullable=true)
*/
private $slug;
/**
* #var int
* #Gedmo\TreeLeft
* #ORM\Column(name="lft", type="integer")
*/
private $lft;
/**
* #var int
* #Gedmo\TreeLevel
* #ORM\Column(name="lvl", type="integer")
*/
private $lvl;
/**
* #var int
* #Gedmo\TreeRight
* #ORM\Column(name="rgt", type="integer")
*/
private $rgt;
/**
* #Gedmo\TreeRoot
* #ORM\ManyToOne(targetEntity="Category")
* #ORM\JoinColumn(name="root", referencedColumnName="id", onDelete="CASCADE")
*/
private $root;
/**
* #Gedmo\TreeParent
* #ORM\ManyToOne(targetEntity="Category", inversedBy="children")
* #ORM\JoinColumn(name="parent", referencedColumnName="id", onDelete="CASCADE")
*/
private $parent;
/**
* #ORM\OneToMany(targetEntity="Category", mappedBy="parent")
* #ORM\OrderBy({"lft" = "ASC"})
*/
private $children;
class DiscountGrid{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="slug", type="string", length=255)
*/
private $slug;
/**
* #var array
*
* #ORM\Column(name="grid", type="array")
*/
private $grid;
First of all, what you are trying to do will be a nightmare if you keep storing DiscountGrid::$grid as an array. Not only this will make your form creation extremely hard, but what will happen if someday you have to add a Category? Will you drag all the indexes to match the new Categories list? This was not your question, and I may be downvoted for suggesting that, but I definitely recommend you build your model a bit cleaner, since having a clean model is mandatory to use FormTypes properly.
What I would suggest is the following model:
DiscountGrid::$grid (rename it to $discounts) is a ManyToOne of a new entity called Discount.
Discount has an attribute $category which is a OneToMany towards Category and an attribute $reduction which is a float.
Once you have this, create a DiscountFormType with a single field reduction which is a PercentType.
Then, create another form DiscountGridFormType with a single field discounts as a CollectionType. This CollectionType should have the option entry_type set as DiscountFormType.
Finally, when you create your form in Controller, bind it a DiscountGrid entity with some Discounts in your discounts attribute. You should see a series of text boxes with percents at the end. That's the list of discounts where you can change values of the reductions.
After that, some form theming will help you display the category name next to the textbox. But I guess you already have some way to go before being at this point.

Doctrine2 Association for ManyToMany Bidirectional and Insert operation for Unique OneToMany Relationships

I am using Symfony2 with Doctrine 2.
I have 5 entities in my application.
Book
Keyword (Bidirectional, should fetch all books having particular keyword)
Author (Bidirectional, should fetch all books having particular author(s))
Category (Bidirectional, should fetch all books falling into particular category)
BookExtra (Unidirectional, In Book Entity, should fetch BookExtra data)
Each book can have many keywords
Each book can have many authors
Each book can fall into a single category
Each book have exactly one BookExtra record.
The keyword and author tables should contain unique values
When a new Book is added, if the Author(s) and Keyword(s) exists, the respected Author ID and Keyword ID should be assigned to the Book, and if it doesn't exist, the new records will be created and the respected ID should be assigned to the Book.
I have the following Entity Classes:
Book.php
namespace Acme\StoreBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Book
*
* #ORM\Table(name="book")
* #ORM\Entity
*/
class Book {
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
*
* #ORM\Column(name="isbn", type="string", length=16)
*/
protected $isbn;
/**
* #var string
*
* #ORM\Column(name="title", type="string", length=255)
*/
protected $title;
/*
* #ORM\OneToOne(targetEntity="BookExtra")
* #ORM\JoinColumn(name="extra_id", referencedColumnName="id")
*
* ********* OR *********
* *********What should go HERE*********
*
*/
protected $bookextra;
/*
* #ORM\ManyToMany(targetEntity="Author", inversedBy="books")
* #ORM\JoinTable(name="authors_books")
*/
protected $author;
/*
* #ORM\OneToOne(targetEntity="Category")
* #ORM\JoinColumn(name="category_id", referencedColumnName="id")
*/
protected $category;
}
BookExtra.php
namespace Acme\StoreBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* BookExtra
*
* #ORM\Table(name="book_extra")
* #ORM\Entity
*/
class Detail {
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
*
* #ORM\Column(name="data", type="string", length=255)
*/
protected $data;
}
Author.php
namespace Bookhut\BookBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Author
*
* #ORM\Table(name="author")
* #ORM\Entity
*/
class Author {
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=100)
*/
protected $name;
// **********What should go HERE*********
protected $books;
}
Keyword & Category Entities are similar to Author Entity
The Problem is that, when i generate schema with cli, it never generates Relationships/Associations.
And what should be the proper Relationships/Associations for Book & Author Entity
I searched for this problem and proper Relationships/Associations
I found this:
Symfony2 app/console not generating properties or schema updates for Entity Relationships/Associations
Saving onetoone relation entities
doctrine2: in a one-to-many bidirectional relationship, how to save from the inverse side?
But it didn't help me.
Can somebody give an example of this type of Relationships/Associations and insert operations?
For author->books:
/**
* #ManyToMany(targetEntity="Author", inversedBy="books")
* #JoinTable(name="authors_books",
* joinColumns={#JoinColumn(name="book_id", referencedColumnName="id")},
* inverseJoinColumns={#JoinColumn(name="author_id", referencedColumnName="id")}
* )
*/
protected $author;
For books->authors
/**
* #ManyToMany(targetEntity="Book", mappedBy="author")
*/
protected $books;
See http://docs.doctrine-project.org/en/latest/reference/association-mapping.html#many-to-many-bidirectional for documentation of many-to-many
See http://docs.doctrine-project.org/en/latest/reference/association-mapping.html for full documentation of associations
EDIT
Is assume all your entities will have setters and getters.
// Create new Author object
$Author = new Author();
// Use setters to set all attributes for this author
// Create new book
$Book = new Book();
// Use setters to set all attributes for book
// Attach book to author
$Author->addBook($Book);
$Book->addAuthor($Author);
The addBook and addAuthor will look like this:
// Inside author entity
public function addBook(Book $Book) {
$this->books->add($Book);
}
// Inside book entity
public function addAuthor($Author) {
$this->authors->add($Author);
}
And add a constructor to both the author and book entities:
public function __construct() {
$this->books = new ArrayCollection();
}
public function __construct() {
$this->authors = new ArrayCollection();
}
Have a look at the documentation to see more examples:
http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/working-with-associations.html

How make query for findBy two users in relation ManyToMany

I have 3 tables Chat(id + info) User(id + some info) and relation table chat_invited(chatId+userId)
I am using ZF2 and Doctrine2
I have Entity chat:
<?php
namespace Chat\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Chat
*
* #ORM\Table(name="chat")
* #ORM\Entity
*/
class Chat
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="title", type="string", length=256, nullable=true)
*/
private $title;
/**
* #var \DateTime
*
* #ORM\Column(name="created", type="datetime", nullable=false)
*/
private $created;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="Chat\Entity\User", inversedBy="chat")
* #ORM\JoinTable(name="chat_invited",
* joinColumns={
* #ORM\JoinColumn(name="chat", referencedColumnName="id")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="user", referencedColumnName="id")
* }
* )
*/
private $user;
/**
* #var \Chat\Entity\ChatCategory
*
* #ORM\ManyToOne(targetEntity="Chat\Entity\ChatCategory")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="category", referencedColumnName="id")
* })
*/
private $category;
/**
* #var \Chat\Entity\User
*
* #ORM\ManyToOne(targetEntity="Chat\Entity\User")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="owner", referencedColumnName="id")
* })
*/
private $owner;
/**
* #var \Chat\Entity\Building
*
* #ORM\ManyToOne(targetEntity="Chat\Entity\Building")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="building", referencedColumnName="id")
* })
*/
private $building;
/**
* #var \Chat\Entity\Company
*
* #ORM\ManyToOne(targetEntity="Chat\Entity\Company")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="company", referencedColumnName="id")
* })
*/
private $company;
/**
* Constructor
*/
public function __construct()
{
$this->user = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Add user
*
* #param \Chat\Entity\User $user
* #return Chat
*/
public function addUser(\Chat\Entity\User $user)
{
$this->user[] = $user;
return $this;
}
/**
* Remove user
*
* #param \Chat\Entity\User $user
*/
public function removeUser(\Chat\Entity\User $user)
{
$this->user->removeElement($user);
}
/**
* Get user
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getUser()
{
return $this->user;
}
........................................
}
How find chat which have invited User1 and User2 to him?
Its worked for me
$qb = $em->createQueryBuilder();
$query = $qb->select('chats, user')
->from('Chat\Entity\Chat', 'chats')
->join('chats.user', 'user')
->join('chats.user', 'user2')
->where('user.id = :user AND user2.id = :inv ')
->setParameter('user', <User1.id>)
->setParameter('inv',<User2.id>)
->setMaxResults(1)
->getQuery();

Symfony2 : How to make a form with a ManyToMany relationship with fields?

Here are my entities :
/**
* Message_User
*
* #ORM\Table(name="message_user")
* #ORM\Entity
* #ORM\HasLifecycleCallbacks()
*/
class Message_User
{
/**
* #ORM\ManyToOne(targetEntity="Learnpack\UserBundle\Entity\User", inversedBy="mu")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
* #ORM\Id
*/
protected $user;
/**
* #ORM\ManyToOne(targetEntity="Learnpack\MessageBundle\Entity\Message", inversedBy="mu")
* #ORM\JoinColumn(name="message_id", referencedColumnName="id")
* #ORM\Id
*/
protected $message;
/**
* #var string $status
*
* #ORM\Column(name="status", type="string", length=45)
*/
private $status;
}
/**
* Message
*
* #ORM\Table(name="message")
* #ORM\Entity
*/
class Message
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="subject", type="string", length=100)
*/
private $subject;
/**
* #var string
*
* #ORM\Column(name="content", type="text")
*/
private $content;
/**
* #var string
*
* #ORM\Column(name="status", type="string", length=45)
*/
private $status;
/**
* #var string
*
* #ORM\Column(name="file", type="string", length=100)
*/
private $file;
/**
* #var \DateTime
*
* #ORM\Column(name="send", type="datetime")
*/
private $send;
/**
* #var \DateTime
*
* #ORM\Column(name="created", type="datetime")
*/
private $created;
/**
* #var \DateTime
*
* #ORM\Column(name="modified", type="datetime")
*/
private $modified;
/**
* #ORM\ManyToOne(targetEntity="Learnpack\UserBundle\Entity\User", inversedBy="user")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
protected $sender;
Now I would like to make a form with basic message sending. There will be three fields:
Recipient, subject and content.
My problem is that I do not know how to add a field "input" with ajax for the recipient.