I have three types of entities,
Users
Groups
Websites
Users can have Websites, and they also can belong to Groups
Each of these entities has a name as well.
Here are my Doctrine2 definitions:
<?php
/** #Entity */
class User
{
// ...
/**
* #Column(type="string",length=255,nullable=false)
* #var string
*/
protected $name;
/**
* #ManyToMany(targetEntity="Group", inversedBy="users")
* #JoinTable(name="users_groups")
*/
private $groups;
/**
* #ManyToMany(targetEntity="Website", inversedBy="users")
* #JoinTable(name="users_websites")
*/
private $websites;
// ...
}
/** #Entity */
class Group
{
// ...
/**
* #Column(type="string",length=255,nullable=false)
* #var string
*/
protected $name;
/**
* #ManyToMany(targetEntity="User", mappedBy="groups")
*/
private $users;
// ...
}
/** #Entity */
class Website
{
// ...
/**
* #Column(type="string",length=255,nullable=false)
* #var string
*/
protected $name;
/**
* #ManyToMany(targetEntity="User", mappedBy="websites")
*/
private $users;
// ...
}
So now if I want to find all Users in a group called "Admins", I can do this:
$group = $em->getRepository("Group")->findOneByName("Admins");
$users = $group->users;
I can also get all users that are associated with website "Google.com" by doing:
$websites = $em->getRepository("Website")->findOneByName("Google.com");
$users = $websites->users;
Now if I want to get all users who are in "Admins", and are also associated with website "Google", what can I do?
If I was using TSQL, I would join the three tables, how do I do that in Doctrine?
Must I use DQL? How would the DQL look like?
You should use DQL for this.
SELECT u
FROM User u
JOIN u.groups g
JOIN u.websites w
WHERE
g.name = :group_name
AND w.name = :website_name
And the php code to do so:
$dql = '...'; // What i've written above
$query = $em->createQuery($dql);
$query->setParameter('group_name', 'Admins');
$query->setParameter('website_name', 'Google');
$users = $query->getResult();
I encourage you to read the doctrine ORM DQL documentation : http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/dql-doctrine-query-language.html
PS: The 2 lines of code you've written, should return groups, and websites, and not users
Related
Why are Proxy classes created instead of entity objects?
DoctrineORMModule\Proxy\__CG__\App\Entity\FormType vs \App\Entity\FormType
Setup: Laminas, Doctrine ORM
Class Project{}
Class ProjectForm
{
/**
* #ORM\Id
* #ORM\Column(name="id")
* #ORM\GeneratedValue
*/
protected $id;
/**
* #ORM\OneToOne(targetEntity="FormType")
* #ORM\JoinColumn(name="form_type_id", referencedColumnName="id")
*/
protected $formType;
/**
* #ORM\OneToOne(targetEntity="Project")
* #ORM\JoinColumn(name="project_id", referencedColumnName="id")
*/
protected $project;
/**
* #ORM\Column(name="label")
*/
protected $label;
/**
* #ORM\Column(name="status")
*/
protected $status;
/**
* #ORM\Column(name="order_nr")
*/
protected $order;
}
Class FormType
{/**
* #ORM\Id
* #ORM\Column(name="id")
* #ORM\GeneratedValue
*/
protected $id;
/**
* #ORM\Column(name="code")
*/
protected $code;
/**
* #ORM\Column(name="label_txt")
*/
protected $label;
:
:
}
Then, using a custom extended Repository use the query builder to get data from storage
$qb->select('pc','ft')
->from(\App\Entity\ProjectForm::class,'pc')
->join(\App\Entity\FormType::class,'ft')
->where($qb->expr()->eq('pc.project',$projectId))
->andWhere('pc.formType=ft.id');
SQL Generated is/seems correct (when passing project ID 1) and returns the correct number of rows
SELECT p0_.id AS id_0, p0_.label AS label_1, p0_.status AS status_2, p0_.order_nr AS order_nr_3, f1_.id AS id_4, f1_.code AS code_5, f1_.label_txt AS label_txt_6, p0_.form_type_id AS form_type_id_7, p0_.project_id AS project_id_8 FROM project_forms p0_ INNER JOIN form_types f1_ WHERE p0_.project_id = 1 AND p0_.form_type_id = f1_.id
The same resultset is visible via
$this->getEntityManager()->getRepository(\Eho\Core\Entity\ProjectForm::class)->findBy(['project'=>$projectId],[]);
With $result[0]->getProject()->getTitle() returning the correct string but $result[0]->getFormType()->getName() throwing and error due to class \DoctrineORMModule\Proxy\__CG__\Entity\FormType being returned from getFormType()...???
Project::getTite() -> string
ProjectForm->getName() -> string
EDIT: Also tried different join for giggles
$joinOn = \Doctrine\ORM\Query\Expr\Join::ON;
$joinWith = \Doctrine\ORM\Query\Expr\Join::WITH;
$qb->select('pf','ft')
->from(\App\Entity\ProjectForm::class,'pf')
->innerJoin(\App\Entity\FormType::class,'ft',$joinWith, 'pf.formType=ft.id')
->where($qb->expr()->eq('pf.project',$projectId));
With SQL generated:
SELECT ...fields... FROM project_forms p0_ INNER JOIN form_types f1_ ON (p0_.form_type_id = f1_.id) WHERE p0_.project_id = 1
But the same resultsets (with Proxy classes are returned)...
Why is ONE entity (project) populated correctly and another (formType) as a proxy...?
I have three entities like following:
1. Customer.php
<?php
//...
/**
* Customer
*
* #ORM\Table(name="customers")
* #ORM\Entity(repositoryClass="CompanyBundle\Repository\CustomerRepository")
* #ORM\HasLifecycleCallbacks
*/
class Customer
{
/**
* #ORM\OneToMany(targetEntity="CustomerAddress", mappedBy="customer")
*/
private $customerAddresses;
// ...
}
?>
2. CustomerAddress.php
<?php
//...
/**
* CustomerAddress
*
* #ORM\Table(name="customer_address")
* #ORM\Entity(repositoryClass="CompanyBundle\Repository\CustomerAddressRepository")
*/
class CustomerAddress
{
/**
* #ORM\ManyToOne(targetEntity="Customer", inversedBy="customerAddresses")
* #ORM\JoinColumn(name="customer_id", referencedColumnName="id", onDelete="CASCADE")
*/
private $customer;
/**
* #ORM\ManyToOne(targetEntity="CustomerAddressType", inversedBy="customerAddresses")
* #ORM\JoinColumn(name="customer_address_type_id", referencedColumnName="id", onDelete="CASCADE")
*/
private $customerAddressType;
//...
}
3. CustomerAddressType.php
<?php
//...
/**
* CustomerAddressType
*
* #ORM\Table(name="customer_address_type")
* #ORM\Entity(repositoryClass="CompanyBundle\Repository\CustomerAddressTypeRepository")
*/
class CustomerAddressType
{
/**
* #ORM\OneToMany(targetEntity="CustomerAddress", mappedBy="customerAddressType")
*/
private $customerAddresses;
//...
}
Here are the rows from table customer_address_type
I want to get all customer addresses of type either 'BA' or 'SA". So I want to remove all other type except these two. Basically I want to do something similiar like query scope in Laravel.
foreach ($customers as $customer) {
// Here I want to filter customer addresses
// Currently its giving me all
$customer_address = $customer->getCustomerAddresses();
}
Is it possible to do like so without using custom query?
You can get an ArrayCollection with all the addresses and then use filter method to get only the ones that you want. You can do it inside the Customer entity so you can reuse it for serialization.
You have to pass a closure to the filter method, and then it iterates over the collection evaluating the closure that should renturn true when you want to include the item in the result or false if not.
I have a GAME table and a SPELL table.
In my game table, I have two spells from the spell table.
//SPELL TABLE
/**
* #ORM\OneToMany(targetEntity="Game", mappedBy="spell")
*/
protected $game;
public function __construct()
{
$this->game = new ArrayCollection();
}
//GAME TABLE
/**
* #ORM\ManyToOne(targetEntity="Spell", inversedBy="game")
* #ORM\JoinColumn(name="spell1", referencedColumnName="id")
*/
protected $spell1;
/**
* #ORM\ManyToOne(targetEntity="Spell", inversedBy="game")
* #ORM\JoinColumn(name="spell2", referencedColumnName="id")
*/
protected $spell2;
In my Symfony2 Profiler I get these messages.
"AppBundle\Entity\Game":
The mappings AppBundle\Entity\Game#spell1 and AppBundle\Entity\Spell#game are inconsistent with each other.
The mappings AppBundle\Entity\Game#spell2 and AppBundle\Entity\Spell#game are inconsistent with each other.
Are these the wrong relations?
I've a ManyToMany relationship between Pais and FabricanteDistribuidor tables defined as follow:
Pais.php
class Pais
{
// column definitions
/**
* #ORM\ManyToMany(targetEntity="AppBundle\Entity\FabricanteDistribuidor", inversedBy="paises", cascade={"persist"})
* #ORM\JoinTable(name="negocio.fabricante_distribuidor_pais", schema="negocio",
* joinColumns={#ORM\JoinColumn(name="fabricante_distribuidor_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="pais_id", referencedColumnName="id")}
* )
*/
protected $fabricanteDistribuidor;
/**
* Add fabricanteDistribuidor
*
* #param AppBundle\Entity\FabricanteDistribuidor $fabricanteDistribuidor
*/
public function addfabricanteDistribuidor(\AppBundle\Entity\FabricanteDistribuidor $fabricanteDistribuidor)
{
$this->fabricanteDistribuidor[] = $fabricanteDistribuidor;
}
/**
* Get fabricanteDistribuidor
*
* #return Doctrine\Common\Collections\Collection
*/
public function getfabricanteDistribuidor()
{
return $this->fabricanteDistribuidor;
}
}
FabricanteDistribuidor.php
class FabricanteDistribuidor
{
// column definitions
/**
* #ORM\ManyToMany(targetEntity="AppBundle\Entity\Pais", mappedBy="fabricanteDistribuidor", cascade={"persist"})
*/
protected $paises;
public function __construct()
{
$this->paises = new ArrayCollection();
}
/**
* Set paises
*
* #param AppBundle\Entity\Pais $pais
* #return FabricanteDistribuidor
*/
public function addPaises(\AppBundle\Entity\Pais $pais)
{
$this->paises[] = $pais;
return $this;
}
/**
* Get paises
*
* #return Doctrine\Common\Collections\Collection
*/
public function getPaises()
{
return $this->paises;
}
}
That will generate a table fabricante_distribuidor_pais on the schema negocio with fabricante_distribuidor_id and pais_id FK pointing to the PK on the related tables, that's fine.
Regarding this scenario:
1- It's possible to define fabricante_distribuidor_id and pais_id as PK on the fabricante_distribuidor_pais table? I mean adding some extra annotation or I need to create a external entity and set them as #ORM\Id on the column definition?
2- Are the addXXX and getXXX methods right in my entities? By right I mean: I should add one or many paises (from Pais entity) to FabricanteDistribuidor easily and I don't care about to the inverse relation meaning I will not add FabricanteDistribuidor from a Pais, are them right or do I need to change something?
1- If one id is a primary key doesn't the relation becomes many to one/ one to many ? Even 1to1 if both are PK
2- If you don't care about the inverse you are going to add getters and setters in only one entity yes. You can still change it to a biredictionnal later with the attribute "mappedBy"
Check if an entity exists :
You can do that in your controller :
for example in Pays
$data = $em->getRepository('AcmeBundle:Pais')->findOneByFabricanteDistribuidor($id);
if($data)
{
// the entity is allready persisted
}
else
{
// no, we can persist the entity
}
I have an Account entity which has a collection of Section entities. Each Section entity has a collection of Element entities (OneToMany association). My problem is that instead of fetching all elements belonging to a section, I want to fetch all elements that belong to a section and are associated with a specific account. Below is my database model.
Thus, when I fetch an account, I want to be able to loop through its associated sections (this part is no problem), and for each section, I want to loop through its elements that are associated with the fetched account. Right now I have the following code.
$repository = $this->objectManager->getRepository('MyModule\Entity\Account');
$account = $repository->find(1);
foreach ($account->getSections() as $section) {
foreach ($section->getElements() as $element) {
echo $element->getName() . PHP_EOL;
}
}
The problem is that it fetches all elements belonging to a given section, regardless of which account they are associated with. The generated SQL for fetching a section's elements is as follows.
SELECT t0.id AS id1, t0.name AS name2, t0.section_id AS section_id3
FROM mydb.element t0
WHERE t0.section_id = ?
What I need it to do is something like the below (could be any other approach). It is important that the filtering is done with SQL.
SELECT e.id, e.name, e.section_id
FROM element AS e
INNER JOIN account_element AS ae ON (ae.element_id = e.id)
WHERE ae.account_id = ?
AND e.section_id = ?
I do know that I can write a method getElementsBySection($accountId) or similar in a custom repository and use DQL. If I can do that and somehow override the getElements() method on the Section entity, then that would be perfect. I would just very much prefer if there would be a way to do this through association mappings or at least by using existing getter methods. Ideally, when using an account object, I would like to be able to loop like in the code snippet above so that the "account constraint" is abstracted when using the object. That is, the user of the object does not need to call getElementsByAccount() or similar on a Section object, because it seems less intuitive.
I looked into the Criteria object, but as far as I remember, it cannot be used for filtering on associations.
So, what is the best way to accomplish this? Is it possible without "manually" assembling the Section entity with elements through the use of DQL queries? My current (and shortened) source code can be seen below. Thanks a lot in advance!
/**
* #ORM\Entity
*/
class Account
{
/**
* #var int
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue
*/
protected $id;
/**
* #var string
* #ORM\Column(type="string", length=50, nullable=false)
*/
protected $name;
/**
* #var ArrayCollection
* #ORM\ManyToMany(targetEntity="MyModule\Entity\Section")
* #ORM\JoinTable(name="account_section",
* joinColumns={#ORM\JoinColumn(name="account_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="section_id", referencedColumnName="id")}
* )
*/
protected $sections;
public function __construct()
{
$this->sections = new ArrayCollection();
}
// Getters and setters
}
/**
* #ORM\Entity
*/
class Section
{
/**
* #var int
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
protected $id;
/**
* #var string
* #ORM\Column(type="string", length=50, nullable=false)
*/
protected $name;
/**
* #var ArrayCollection
* #ORM\OneToMany(targetEntity="MyModule\Entity\Element", mappedBy="section")
*/
protected $elements;
public function __construct()
{
$this->elements = new ArrayCollection();
}
// Getters and setters
}
/**
* #ORM\Entity
*/
class Element
{
/**
* #var int
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
protected $id;
/**
* #var string
* #ORM\Column(type="string", length=50, nullable=false)
*/
protected $name;
/**
* #var Section
* #ORM\ManyToOne(targetEntity="MyModule\Entity\Section", inversedBy="elements")
* #ORM\JoinColumn(name="section_id", referencedColumnName="id")
*/
protected $section;
/**
* #var \MyModule\Entity\Account
* #ORM\ManyToMany(targetEntity="MyModule\Entity\Account")
* #ORM\JoinTable(name="account_element",
* joinColumns={#ORM\JoinColumn(name="element_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="account_id", referencedColumnName="id")}
* )
*/
protected $account;
// Getters and setters
}
If I understand correctly, you want to be able to retrieve all Elements of all Sections of an Account, but only if those Elements are associated with that Account, and this from a getter in Account.
First off: An entity should never know of repositories. This breaks a design principle that helps you swap out the persistence layer. That's why you cannot simple access a repository from within an entity.
Getters only
If you only want to use getters in the entities, you can solve this by adding to following 2 methods:
class Section
{
/**
* #param Account $accout
* #return Element[]
*/
public function getElementsByAccount(Account $accout)
{
$elements = array();
foreach ($this->getElements() as $element) {
if ($element->getAccount() === $account) {
$elements[] = $element->getAccount();
}
}
return $elements;
}
}
class Account
{
/**
* #return Element[]
*/
public function getMyElements()
{
$elements = array()
foreach ($this->getSections() as $section) {
foreach ($section->getElementsByAccount($this) as $element) {
$elements[] = $element;
}
}
return $elements;
}
}
Repository
The solution above is likely to perform several queries, the exact amount depending on how many Sections and Elements are associated to the Account.
You're likely to get a performance boost when you do use a Repository method, so you can optimize the query/queries used to retrieve what you want.
An example:
class ElementRepository extends EntityRepository
{
/**
* #param Account $account [description]
* #return Element[]
*/
public function findElementsByAccount(Account $account)
{
$dql = <<< 'EOQ'
SELECT e FROM Element e
JOIN e.section s
JOIN s.accounts a
WHERE e.account = ?1 AND a.id = ?2
EOQ;
$q = $this->getEntityManager()->createQuery($dql);
$q->setParameters(array(
1 => $account->getId(),
2 => $account->getId()
));
return $q->getResult();
}
}
PS: For this query to work, you'll need to define the ManyToMany association between Section and Account as a bidirectional one.
Proxy method
A hybrid solution would be to add a proxy method to Account, that forwards the call to the repository you pass to it.
class Account
{
/**
* #param ElementRepository $repository
* #return Element[]
*/
public function getMyElements(ElementRepository $repository)
{
return $repository->findElementsByAccount($this);
}
}
This way the entity still doesn't know of repositories, but you allow one to be passed to it.
When implementing this, don't have ElementRepository extend EntityRepository, but inject the EntityRepository upon creation. This way you can still swap out the persistence layer without altering your entities.