Symfony2 Entity ManyToMany Relation Data Structure - database

I have the following setup:
Entity: 'Customers'
Entity: 'Accounts'
Those entities are in a #ManyToMany relation.
So I have the following database tables:
customers
accounts
customers_accounts
Now I need to save data for each customer for each account. Example:
There is one customer 'Tom'. Two accounts 'Ben' and 'Eric' are in charge of customer 'Tom'. Now I need to save whether or not account 'Ben' has already spoken to customer 'Tom'. Also I need to save the same status for account 'Eric'.
What's the best way to organise the database here? Best thing would be that there is an extra column in the table 'customers_accounts'. Is that possible? What other options are there?
Thanks for your help!
Just to show you how the entities are linked to each other:
/**
* #ORM\ManyToMany(targetEntity="AppBundle\Entity\Customer", inversedBy="accounts", cascade={"persist"})
* #ORM\JoinTable(name="customers_accounts")
**/
protected $customers;

In ManyToMany you can't add additional fields in your junction table i.e customers_accounts , to have an additional fields for your junction table you have to tweak your mappings as create a junction entity which will point your customer and accounts entity in ManyToOne way and your customer and accounts entities will point back to your junction entity in a OneToMany way
OneToMany OneToMany
-----------> <------------
Customer CustomerHasAccounts Accounts
<---------- ------------>
ManyToOne ManyToOne
Customer Entity
/**
* Customer
* #ORM\Table(name="customer")
* #ORM\Entity
*/
class Customer
{
/**
* #ORM\OneToMany(targetEntity="NameSpace\YourBundle\Entity\CustomerHasAccounts", mappedBy="customers",cascade={"persist","remove"} )
*/
protected $hasAccounts;
}
Accounts Entity
/**
* Accounts
* #ORM\Table(name="accounts")
* #ORM\Entity
*/
class Accounts
{
/**
* #ORM\OneToMany(targetEntity="NameSpace\YourBundle\Entity\CustomerHasAccounts", mappedBy="acccounts",cascade={"persist","remove"} )
*/
protected $hasCustomers;
}
CustomerHasAccounts Entity
/**
* CustomerHasAccounts
* #ORM\Table(name="customers_accounts")
* #ORM\Entity
*/
class CustomerHasAccounts
{
/**
* #ORM\ManyToOne(targetEntity="NameSpace\YourBundle\Entity\Accounts", cascade={"persist"}, fetch="LAZY")
* #ORM\JoinColumn(name="acccount_id", referencedColumnName="id")
*/
protected $acccounts;
/**
* #ORM\ManyToOne(targetEntity="NameSpace\YourBundle\Entity\Customer", cascade={"persist","remove"} , fetch="LAZY" )
* #ORM\JoinColumn(name="customers_id", referencedColumnName="id",nullable=true)
*/
protected $customers;
/**
*
* #ORM\Column(name="status", type="string")
*/
protected $status;
}

You have to transform your ManyToMany relation between your entities by a OneToMany-ManyToOne entity making the link between your 2 ManyToMany entities, this entity will have all the data related to this relation.
Customer
Class Customer
{
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\CustomerAccount", mappedBy="societe", cascade={"Persist"})
*/
private $customerAccounts;
}
Account
Class Account
{
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\CustomerAccount", mappedBy="account", cascade={"Persist"})
*/
private $customerAccounts;
}
CustomerAccount
Class CustomerAccount
{
/**
* #ORM\Id
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Customer", inversedBy="customerAccounts")
*/
private $societe;
/**
* #ORM\Id
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Account", inversedBy="customerAccounts")
*/
private $contact;
/**
* #var boolean
*
* #ORM\Column(name="alreadySpoken", type="boolean")
*/
private $alreadySpoken;
}

Related

Doctrine ORM - Relationship between same object

im stuck implementing aa probably easy database relationship.
I have an ORM object like
{ id, name, type , relationships }
and an relationship object
{ relationshipType, object1 , object2 }
What i try to accomplish is that when i create a relationship beween two objects i want to see the relationship object in both objects in the "relationships" collection.
Right now, only e.g. object 1 has the relationship object since thats the property with the "inversedBy" keyword.
Thanks in advance
It should looks like this:
class ClassA {
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\OneToMany(targetEntity="App\Entity\ClassB", mappedBy="objectA")
*/
private $objectsB;
/**
* #ORM\OneToMany(targetEntity="App\Entity\ClassB", mappedBy="objectB")
*/
private $objectsA;
}
class ClassB {
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=20)
*/
private $relationshipType;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\ClassA", inversedBy="objectsB")
* #ORM\JoinColumn(nullable=false)
*/
private $objectA;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\ClassA", inversedBy="objectsA")
* #ORM\JoinColumn(nullable=false)
*/
private $objectB;
}

Configure doctrine queries generation to lowercase

I have a sql error deploying my symfony project on Unix. Indeed, the query made uses uppercase for table names which was not the case before. In the database, table names are lowercases.
Does anybody know where you configure how you want the queries generation be made (uppercase or lowercase)
Thank you.
Maybe something in Doctrine configuration??
NOTE : I have some new information.
I asked to rebuild my database from the save at a time I know it was working.
I have some errors because, for the new code, the database must be a little different than what it was at this time but I can see that in queries the names of the tables are in lower case.
I pass my new sql (the same as before plus some little changes) in command line.
\. path/to/my/sql
I launch the site and queries are made with table names in uppercase.
Got any idea ?
example of entity :
<?php
namespace MyBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* MyTable
*
* #ORM\Table(name="mytable")
* #ORM\Entity(repositoryClass="MyBundle\Repository\MyClassRepository")
*/
class MyTable
{
/**
* #var string
*
* #ORM\Column(name="FIELD1, type="string", length=120, nullable=false)
*/
private $field1;
/**
* #var string
*
* #ORM\Column(name="FIELD2", type="string", length=50, nullable=true)
*/
private $field2
/**
* Set field1
*
* #param string $field1
*
* #return Tretb
*/
public function setField1($field1)
{
$this->field1 = $field1;
return $this;
}
/**
* Get field1
*
* #return string
*/
public function getField1()
{
return $this->field1;
}
/**
* Set field2
*
* #param string $field2
*
* #return Tretb
*/
public function setField2($field2)
{
$this->field2 = $field2;
return $this;
}
/**
* Get field2
*
* #return string
*/
public function getField2()
{
return $this->field2;
}
}
Dont know if you can configure it more generally, but you can define table table for each entity with doctrine
/**
* AppBundle\Entity\MyEntity
*
* #ORM\Table()
* #ORM\Entity
* #ORM\Table(name="mytable")
*/
class MyEntity
{
Does your MySQL instance support lowercase tablenames ?
To check the settings use:
mysql> show variables like "lower_case%";
To change the setting you need to change the mysql setting
lower_case_table_names = 1 or lower_case_table_names = 2
Source from Stackoverflow

How can I use 'foreign key' on doctrine?

I am making the lesson administration system on symfony2 and doctrine
I am confused to use foreign key in doctrine.
/Entity/User.php
class User extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*#ORM\OneToOne(targetEntity="Acme\UserBundle\Entity\Lesson", inversedBy("teacher"))
*/
protected $id;
.
.
}
/Entity/Lesson.php
class Lesson
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
*
* #ORM\OneToOne(targetEntity="Acme\UserBundle\Entity\User", inversedBy("id"))
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
private $teacher;
.
.
}
Each 'Lesson' has one teacher registered in User.php.
How can I write annotation for this purpose?
I am also planning that each Lesson has multiple students from /Entity/User.
How can I write annotation for this purpose? (ManyToMany?)
I have researched ,but I couldn't find good documents for doctrine annotation.
Here some cheat sheets for doctrine annotations : link
For your problem, you need to define your variables in each side of your associations.
In Lesson.php :
/**
* #ORM\OneToOne(
* targetEntity="Acme\UserBundle\Entity\User",
* inversedBy="lessons*removethis : name of the variable in user.php*"
* )
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
private $teacher;
In User.php :
/**
* #ORM\OneToOne(
* targetEntity="Acme\UserBundle\Entity\Lesson",
* mappedBy="teacher*removethis : name of the variable in lesson.php*"
* )
*/
private $lessons;
And yes, ManyToMany is good for the purpose your are looking for :)

Saving Many to Many relationship to database in Symfony2

In my Symfony2 project I have two related entities: Users and Favorites. They have a many-to-many relationship.
My application works as follows:
In my Twig-page I have an few items with a button 'Add to Favorites'. When you click the button my controller saves the item_id in the Favorites column. But then I want to save
the user who added the item to his favorites and here my application fails.
The User and the favorite exist but the joincolumn between Users and Favorites remains empty.
I also don't receive any kind of errors.
Here is my code:
Entity Users
class Users implements AdvancedUserInterface
{
/**
* #var \Doctrine\Common\Collections\ArrayCollection
*
* #ORM\ManyToMany(targetEntity="Favorites", inversedBy="user", cascade={"persist"})
* #ORM\JoinTable(name="user_has_favorite",
* joinColumns={
* #ORM\JoinColumn(name="user_id", referencedColumnName="user_id")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="favorite_id", referencedColumnName="favorite_id")
* }
* )
*/
private $favorite;
public function __construct()
{
$this->favorite = new \Doctrine\Common\Collections\ArrayCollection();
}
public function addFavorite(\Geo\CityTroopersBundle\Entity\Favorites $favorite)
{
$this->favorite[] = $favorite;
return $this;
}
...
Entity Favorites
class Favorites
{
/**
* #var \Doctrine\Common\Collections\ArrayCollection
*
* #ORM\ManyToMany(targetEntity="Users", mappedBy="favorite", cascade={"persist"})
*/
private $user;
public function __construct()
{
$this->user = new \Doctrine\Common\Collections\ArrayCollection();
}
public function addUser(\Geo\CityTroopersBundle\Entity\Users $user)
{
$this->user[] = $user;
return $this;
}
My controller
public function showNewsAction()
{
$request = $this->get('request');
$itemId=$request->request->get('itemId');
if($itemId != NULL)
{
//MAKE NEW FAVORITE AND ADD TO DATABASE LINKED WITH ITEM
$favorite = new Favorites();
$favorite->setItemId($itemId);
//LINK FAVORITE ID WITH USER ID IN JOINCOLUMN
$userId = 6;
$em = $this->getDoctrine()->getEntityManager();
$user = $em->getRepository('GeoCityTroopersBundle:Users')->find($userId);
$favorite->addUser($user);
$em->persist($favorite);
//I TRIED THIS TOO, BUT IT FAILED
/*$user->addFavorite($favorite);
$em->persist($user);*/
$em->flush();
You were close there. For doctrine many-to-many relationships, you need to call both add methods
$favorite->addUser($user);
$user->addFavorite($favorite);
$em->persist($favorite);
$em->persist($user);
$em->flush();
This should do the trick. In the docs they do this, but don't mention it too explicitly. Not sure why either because lots of people run into this (myself included).
As explained here, only the owning side is responsible for the connection management :
http://doctrine-orm.readthedocs.org/en/latest/reference/association-mapping.html#owning-and-inverse-side-on-a-manytomany-association
So only
$user->addFavorite($favorite);
should persist, and not
$favorite->addUser($user);
Like indicated by Cedric, adding a record for a many to many relation is done only in one direction and it depends on how you defined the relation: adding can be done only by the parent entity of the relation, so in your case you must use:
$user->addFavorite($favorite);
In your line :
#ORM\JoinColumn(name="favorite_id", referencedColumnName="favorite_id")
The
name="favorite_id"
part refers to the columns in the join table, whereas the
referencedColumnName="favorite_id"
refers to the id in the favorite table which usualy is simply "id". You should try :
/**
* #var \Doctrine\Common\Collections\ArrayCollection
*
* #ORM\ManyToMany(targetEntity="Favorites", inversedBy="user", cascade={"persist"})
* #ORM\JoinTable(name="user_has_favorite",
* joinColumns={
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="favorite_id", referencedColumnName="id")
* }
* )
*/
private $favorite;

Working example of joining two tables with join table using Doctrine 2

Doctrine has got some nice documentation, but at some point I have the feeling for someone who wants to get in to doctrine it is sort of a small battle to get used to the mapping stuff. I am one of those guys who belongs to this section. I have gone through most of the mapping stuff documentation for example like this and other links in doctrine official site, but the documentation for me looks like bits and pieces to follow. I am saying this for my case.
Is there somewhere an example which shows how can I join two tables with a third join table, I wanted to know the basic mapping for this schema.
Let me say I have two tables: Fruits and Country.
The relationship is that one country produces many varieties of fruits, so as to say that is a onetomany and manytoone relationship. Apart from that I wanted to do association using a third table say countryFruits.
Fruits Table
-- fruitsId (PK, AI)
-- fruitName
Country Table
-- countryId (PK, AI)
-- countryName
countryFruits Table
-- fruitsId (PK, FK)
-- countryId (PK, FK)
That is how the tables in MySQL look like and it has already been designed. Now I can fill the fruits table with doctrine and when it comes to filling the country table, I get a messed up mapping problem.
/**
* #ORM\Entity
* #ORM\Table(name="fruits")
* #property string $fruitName
* #property int $fruitId
*/
class Fruits
{
/**
* #ORM\Id
* #ORM\Column(type="integer", name="fruitId", unique=true);
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $fruitId;
/**
* #ORM\Column(type="string")
*/
protected $fruitName;
/**
* #ORM\OneToMany(targetEntity="Country", mappedBy="fruits", cascade={"persist"})
*/
protected $country;
public function __get($property)
{
return $this->$property;
}
public function __set($property, $value)
{
$this->$property = $value;
}
}
/**
* #ORM\Entity
* #ORM\Table(name="country")
* #property string $countryName
* #property int $countryId
*/
class Country
{
/**
* #ORM\Id
* #ORM\Column(type="integer", name="countryId", unique=true);
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $countryId;
/**
* #ORM\Column(type="string")
*/
protected $countryName;
/**
* #ORM\OneToMany(targetEntity="Fruits", mappedBy="country", cascade={"persist"})
*/
protected $countries;
public function __get($property)
{
return $this->$property;
}
public function __set($property, $value)
{
$this->$property = $value;
}
}
/**
* #ORM\Entity
* #ORM\Table(name="countryFruits ")
* #property int $fruitId
* #property int $countryId
*/
class countryFruits
{
/**
* #ORM\Id
* #ORM\Column(type="integer", name="fruitId", nullable=false)
* #ORM\GeneratedValue(strategy="NONE")
*/
protected $fruitId;
/**
* #ORM\Id
* #ORM\Column(type="integer", name="countryId", nullable=false)
* #ORM\GeneratedValue(strategy="NONE")
*/
protected $countryId;
/**
* #ORM\ManyToOne(targetEntity="Country", inversedBy="fruits", cascade={"persist"})
* #ORM\JoinColumn(name="countryId", referencedColumnName="countryId")
*/
protected $country;
/**
* #ORM\ManyToOne(targetEntity="Fruits", inversedBy="country", cascade={"persist"})
* #ORM\JoinColumn(name="fruitId", referencedColumnName="fruitId")
*/
protected $fruits;
/**
* Set fruits
*
* #param Fruits $fruits
*/
public function setFruits($fruits)
{
$this->fruits = $fruits;
}
/**
* ´Get fruits
*
* #param Fruits $fruits
*/
public function getFruits()
{
return $this->fruits;
}
/**
* Set country
*
* #param Country $country
*/
public function setCountry($country)
{
$this->country = $country;
}
/**
* Get country
*
* #param Country $country
*/
public function getCountry($country)
{
$this->country = $country;
}
}
Can somebody cross check this and let me know if my mappings are done in the proper way. In case, is it possible to get a small piece of code how to persist the entities into my database.
you don't need the countryFruits class. what you're searching for is the ManyToMany relation! also you don't want to name entities in plural, as an entity always represends a single object/row in the table.
Fruit entity
/**
* #ORM\Entity
* #ORM\Table(name="fruits")
* #property string $fruitName
* #property int $fruitId
*/
class Fruit
{
/**
* #ORM\ManyToMany(targetEntity="Country")
* #ORM\JoinTable(name="country_fruits",
* joinColumns={#ORM\JoinColumn(name="country_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="fruit_id", referencedColumnName="id")}
* )
* #var Country[]
*/
protected $countries;
}
Country entity
/**
* #ORM\Entity
* #ORM\Table(name="country")
* #property string $countryName
* #property int $countryId
*/
class Country
{
/**
* #ORM\ManyToMany(targetEntity="Fruit")
* #ORM\JoinTable(name="country_fruits",
* joinColumns={#ORM\JoinColumn(name="fruit_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="country_id", referencedColumnName="id")}
* )
* #var Fruit[]
*/
protected $fruits;
}
note that you don't need the countryFruits class, but the table country_fruits is required!

Resources