I use Symfony and Doctrine for mapping database , I have 2 entities "Product" and "Operation" with ManyToMany relation so I get an other table in DataBase called "Products-Operations"
Now I like to add an attribute for this table , how can I do it?
Produit.orm.yml
manyToMany:
operations:
targetEntity: Operation
mappedBy: produits
Operation.orm.yml
manyToMany:
produits:
targetEntity: Produit
inversedBy: operations
joinTable:
name: produits_operations
joinColumns:
operation_id:
referencedColumnName: id
inverseJoinColumns:
produit_id:
referencedColumnName: id
I work with annotation to create table in data base I think same orm.yml and hope this solution is work...
//inverse side
class Product
{
/**
* #ORM\OneToMany(targetEntity="ProductOperation", mappedBy="product", cascade={"persist", "remove"})
*/
private $productOperations;
}
//owing side
class ProductOperation
{
/**
* #ORM\ManyToOne(targetEntity="Product", inversedBy="productOperations")
*/
private $product;
/**
* #ORM\ManyToOne(targetEntity="Operation", inversedBy="productOperations")
*/
private $operation;
}
//inverse side
class Operation
{
/**
* #ORM\OneToMany(targetEntity="ProductOperation", mappedBy="operation", cascade={"persist", "remove"})
*/
private $productOperations;
}
Related
How do you declare joinColumns/composite keys with PHP attributes. Haven't been able to find the right way and it is not documented (https://www.doctrine-project.org/projects/doctrine-orm/en/2.11/reference/attributes-reference.html)
Entities
Comment.php
#[ORM\Entity(repositoryClass: CommentRepository::class)]
class Comment
{
#[ORM\Id]
#[ORM\Column(type: 'integer')]
private $id;
#[ORM\ManyToOne(targetEntity: PullRequest::class, inversedBy: 'comments')]
#[ORM\JoinColumn(name: 'pull_request_id', referencedColumnName: 'id')]
#[ORM\JoinColumn(name: 'repo_id', referencedColumnName: 'repo_id')]
private $pullRequest;
}
PullRequest.php
#[ORM\Entity(repositoryClass: PullRequestRepository::class)]
class PullRequest
{
#[ORM\Id]
#[ORM\Column(type: 'integer', unique: false)]
private $id;
#[ORM\Id]
#[ORM\ManyToOne(targetEntity: Repo::class, inversedBy: 'pullRequests')]
#[ORM\JoinColumn(nullable: false)]
private $repo;
#[ORM\OneToMany(mappedBy: 'pullRequest', targetEntity: Comment::class, orphanRemoval: true)]
private $comments;
}
I ran into the same issue today and managed to find a workaround. It indeed seems like JoinColumns is not available as a PHP8 attribute, at least not at Doctrine ORM 2.11 nor the upcoming 2.12 / 3.0.
However, you can work around this by moving the join columns definitions into an AssociationsOverride attribute at the class level as follows:
#[ORM\Entity(repositoryClass: CommentRepository::class)]
#[ORM\AssociationOverrides([
new ORM\AssociationOverride(
name: 'pullRequest',
joinColumns: [
new ORM\JoinColumn(name: 'pull_request_id', referencedColumnName: 'id'),
new ORM\JoinColumn(name: 'repo_id', referencedColumnName: 'repo_id')
]
)
])]
class Comment
{
#[ORM\Id]
#[ORM\Column(type: 'integer')]
private $id;
#[ORM\ManyToOne(targetEntity: PullRequest::class, inversedBy: 'comments')]
private $pullRequest;
}
According to https://github.com/greg0ire/doctrine-orm/commit/18366db5789b03e1d8a34933fbbff97a768a9cfe the "JoinColumns" attribute is no longer required, multiple "JoinColumn" attributes are sufficient.
My entity Society has a relation in OneToMany with Client.
Class Society :
/** #var Collection<int, Client> */
#[ORM\OneToMany(mappedBy: 'society', targetEntity: Client::class, cascade: ['persist', 'remove'])]
#[Assert\Valid]
private Collection $clients;
class Client:
#[ORM\ManyToOne(targetEntity: Society::class, cascade: ['persist', 'remove'], inversedBy: 'clients')]
#[Assert\Valid]
private ?Society $society = null;
In Client's class, I've got a boolean property isSigned. and I would like to put a BooleanFilter on it. If I use EntityFilter, I can only filter by the name of Client and If I try to do BooleanFilter('client.IsSigned') I've got an error.
Any idea to add a booleanFilter on my Association ?
I've the following entity Category defined in YML with bi-directional many-to-many relationship. When i try to load the fixtures data in the corresponding database via doctrine:fixtures:load i receive a PDO Exception error 1048 about integrity violation that the 'name' field can't be null
# src/tuto/JobeetBundle/Resources/config/doctrine/Category.orm.yml
tuto\JobeetBundle\Entity\Category:
type: entity
repositoryClass: tuto\JobeetBundle\Repository\CategoryRepository
table: category
id:
id:
type: integer
generator: { strategy: AUTO }
fields:
name:
type: string
length: 255
unique: true
slug:
type: string
length: 255
unique: true
oneToMany:
jobs:
targetEntity: Job
mappedBy: category
manyToMany:
affiliates:
targetEntity: Affiliate
mappedBy: categories
lifecycleCallbacks:
prePersist: [setSlugValue]
preUpdate: [setSlugValue]
/**
* #var string
*/
private $slug;
public
function setSlug($slug) {
$this - > slug = $slug;
return $this;
}
/**
* Get slug
*
* #return string
*/
public
function getSlug() {
return $this - > slug;
}
/**
* #ORM\PrePersist
* #ORM\PreUpdate
*/
public
function setSlugValue() {
$sl = new Slugify();
$this - > slug = $sl - > slugify($this - > getName());
}
/**
* #ORM\PrePersist
* #ORM\PreUpdate
*/
public
function prePersist() {
$this - > slug = '';
}
May you find the fixture here
You have a typo $qualityManager object on line 20:
Here:
$qualityManager = new Category();
$technician->setName("Quality Manager"); // <-- Wrong object
Try this:
$qualityManager = new Category();
$qualityManager->setName("Quality Manager");
Hope this help
I've finally succeeded to create a working self-referencing relationship in Doctrine/Symfony2. But, when I request a findAll the table rows aren't returned in the order I want. (Maybe it's not THAT easy, but I can't find any solution anymore.)
The table "categories"
id parentId name
1 NULL music
2 NULL films
3 1 bands
4 1 guitars
5 NULL books
6 2 actors
The file "category.orm.yml"
FormBundle\Entity\Category:
type: entity
oneToMany:
children:
fetch: "EAGER"
targetEntity: FormBundle\Entity\Category
mappedBy: parent
cascade: ["all"]
manyToOne:
parent:
targetEntity: FormBundle\Entity\Category
inversedBy: children
joinColumn:
name: parentId
referencedColumnName: id
table: categories
repositoryClass: FormBundle\Entity\CategoryRepository
id:
id:
column: id
type: integer
id: true
generator:
strategy: AUTO
fields:
name:
type: string
length: '100'
lifecycleCallbacks: { }
I tried an orderBy (in any way I could find, on any field) but I haven't succeeded or had ANY progress with it.
The entity file "Category.php"
<?php
namespace FormBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* Category
*/
class Category
{
/**
* #var integer
*/
private $id;
/**
* #var category
*/
private $parent;
/**
* #var arrayCollection
*/
private $children;
/**
* #var string
*/
private $name;
public function __construct()
{
$this->children = new ArrayCollection();
}
public function getChildren() {
return $this->children;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set parentId
*
* #param integer $parentId
* #return Category
*/
public function setParent(Category $parent)
{
$this->parent = $parent;
return $this;
}
/**
* Get parentId
*
* #return integer
*/
public function getParent()
{
return $this->parent;
}
/**
* Set name
*
* #param string $name
* #return Category
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
}
What I want as output
<b>music</b>
bands
guitars
<b>films</b>
actors
<b>books</b>
This will be a list, but let's not worry about that right now! It's about the order!
My question
What do I put in my controller to use the relations and fetch the rows in the order I want? Or even better; what do I put in the controller and the repository?
I don't want to use DQL since that is not how Doctrine is meant to be used. I want to learn Doctrine and this is seems to be a very good thing to learn. Yes, I have read the docs for a few days, but nothing seems to work for me. Maybe I overlooked something.
Your tree depth will likely be > 1, Doctrine extensions with his Tree-NestedSet will be a good pick. If it's not the case, your question becomes trivial :
In your controller :
$parentCategories = $categoryRepository->findBy(array('parent' => null));
return $this->render('path_to_your_view.html.twig', array(
'parentCategories' => $parentCategories
));
In your view :
{% for parentCategory in parentCategories %}
<b>{{ parentCategory.getName() | e }}</b>
{% for childCategory in parentCategory.getChildren() %}
<p>{{ childCategory.getName() | e }}</p>
{% endfor %}
{% endfor %}
When i translate an entity, everything is fine but slug.
My entity:
/**
* #Gedmo\Translatable
* #var string
*/
private $slug;
My Orm.yml
slug:
type: string
length: 1000
nullable: false
gedmo:
translatable: {}
slug:
separator: -
fields:
- title
My ext_translations table:
Title and content successfully translated to given language. Slug is generating over title in posts table. I could not translate slug.
Any idea?
I suggest you to change from Doctrine Extensions to DoctrineBehaviors, because the development of the doctrine extensions has stopped. Also what you want is easily possible with doctrine behaviour:
Your Entity class:
class Entity {
use ORMBehaviors\Translatable\Translatable;
}
Your EntityTranslation class:
class EntityTranslation {
use ORMBehaviors\Translatable\Translation;
use ORMBehaviors\Sluggable\Sluggable;
/**
* #var string
* #ORM\Column(type="text", nullable=true)
*/
protected $title;
public function getSluggableFields()
{
return [ 'title' ];
}
}