Doctrine ORM Bind Product to Multiple Entities - php

I have businesses, categories and products. Categories are assigned to businesses and products are assigned to categories and businesses.
Reason being, one product can be assigned to different categories in different businesses.
Business and Category entities are working fine, but I am not sure how to write a Product entity to achieve what I need...
Business Entity:
namespace Raiel\AFMage\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity()
* #ORM\Table(name="businesses")
*/
class Business {
/**
* #ORM\Id()
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer", name="id")
*/
private $id;
/**
* #ORM\Column(name="name", type="string", length=64)
*/
private $name;
/**
*
* #ORM\ManyToMany(targetEntity="Category", inversedBy="businesses")
* #ORM\JoinTable(
* name="business_categories",
* joinColumns={
* #ORM\JoinColumn(name="business_id", referencedColumnName="id")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="category_id", referencedColumnName="id")
* }
* )
*/
private $categories;
/**
* Default constructor, initializes collections
*/
public function __construct() {
$this->categories = new ArrayCollection();
}
}
Category Entity:
<?php
namespace Raiel\AFMage\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
/**
* #Gedmo\Tree(type="nested")
* #ORM\Table(name="categories")
* #ORM\Entity(repositoryClass="Gedmo\Tree\Entity\Repository\NestedTreeRepository")
*/
class Category {
/**
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue
*/
private $id;
/**
*
* #ORM\ManyToMany(targetEntity="Business", mappedBy="categories")
*/
private $businesses;
/**
* #Gedmo\TreePath
* #ORM\Column(name="path", type="string", length=3000, nullable=true)
*/
private $path;
/**
* #ORM\Column(name="title", type="string", length=64)
*/
private $title;
/**
* #Gedmo\TreeLevel
* #ORM\Column(name="lvl", type="integer")
*/
private $lvl;
/**
* #Gedmo\TreeLeft
* #ORM\Column(name="lft", type="integer")
*/
private $lft;
/**
* #Gedmo\TreeRight
* #ORM\Column(name="rgt", type="integer")
*/
private $rgt;
/**
* #Gedmo\TreeRoot
* #ORM\Column(name="root", type="integer", nullable=true)
*/
private $root;
/**
* #Gedmo\TreeParent
* #ORM\ManyToOne(targetEntity="Category", inversedBy="children")
* #ORM\JoinColumn(name="parent_id", referencedColumnName="id", onDelete="CASCADE")
*/
private $parent;
/**
* #ORM\OneToMany(targetEntity="Category", mappedBy="parent")
* #ORM\OrderBy({"lft" = "ASC"})
*/
private $children;
/**
* Constructor
*/
public function __construct() {
$this->children = new ArrayCollection();
$this->businesses = new ArrayCollection();
}
}
Also, $business->addCategory works fine but $category->addBusiness doesn't save to DB.

Your product entity will probably look something like:
namespace Raiel\AFMage\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity()
* #ORM\Table(name="products")
*/
class Product {
/**
* #ORM\Id()
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer", name="id")
*/
private $id;
/**
* #ORM\Column(name="name", type="string", length=64)
*/
private $name;
/**
*
* #ORM\ManyToMany(targetEntity="Category", inversedBy="products")
* #ORM\JoinTable(
* name="product_categories",
* joinColumns={
* #ORM\JoinColumn(name="product_id", referencedColumnName="id")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="category_id", referencedColumnName="id")
* }
* )
*/
private $categories;
/**
*
* #ORM\ManyToMany(targetEntity="Business", inversedBy="products")
* #ORM\JoinTable(
* name="product_businesses",
* joinColumns={
* #ORM\JoinColumn(name="product_id", referencedColumnName="id")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="business_id", referencedColumnName="id")
* }
* )
*/
private $businesses;
}
So more or less what you have for your Business entity but with the ManyToMany relation using a different join table.
And to make $category->addBusiness() work then you'll probably want to add a cascade option to category, thusly:
/**
*
* #ORM\ManyToMany(targetEntity="Business", mappedBy="categories", cascade="persist")
*/
private $businesses;
This informs Doctrine that anything new added to the $businesses array collection should be persisted, take a look at the documentation for details.

Related

How to get a list of all the brands of my product entity?

I am new to both Symfony and API platform and trying to understand how to get all unique brands and product types of my products in a list so that I can use them later to display a list of filters to use in my frontend.
I'm a bit lost as to how to do this. I want to have a custom endpoint products/filters that would return me the list.
I would like to have it in this form:
{
brands: [
"Agilent",
"Comtr"
"Anot
],
types:[
"Accelerometer",
"Sonometer",
"Micro-amplifier"
]
}
Both brand and type are nested properties of my entity Product, they come from my entity ProductModel. I am using Api platform for my api that is why there is a lot of annotations.
class Product
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
* #Groups({"product_get", "product_list"})
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity=ProductModel::class, cascade={"persist"})
* #ORM\JoinColumn(nullable=false)
* #Groups({"product_get", "product_list"})
*/
private $idProductModel;
/**
* #ORM\Column(type="string", length=50)
* #Groups({"product_get", "product_list"})
* #Assert\NotBlank(message="The field serial number is mandatory.")
*/
private $serialNumber;
/**
* #ORM\Column(type="text", nullable=true)
* #Groups({"product_get"})
*/
private $comment;
/**
* #ORM\Column(type="datetime")
* #Groups({"product_get", "product_list"})
*/
private $createdAt;
/**
* #ORM\Column(type="datetime", nullable=true)
* #Groups({"product_get", "product_list"})
*/
private $updatedAt;
/**
* #ORM\Column(type="datetime", nullable=true)
* #Groups({"product_get"})
*
*/
private $deletedAt;
/**
* #ORM\Column(type="boolean")
* #Groups({"product_get", "product_list"})
* #Assert\NotBlank(message="The field confidential is mandatory.")
*
*/
private $confidential;
/**
* #ORM\ManyToOne(targetEntity=Storage::class, cascade={"persist"})
* #Groups({"product_get", "product_list"})
*/
private $idStorage;
/**
* #ORM\ManyToOne(targetEntity=User::class, cascade={"persist"})
* #ORM\JoinColumn(nullable=false)
* #Groups({"product_get", "product_list"})
*/
private $idUser;
/**
* #ORM\ManyToOne(targetEntity=User::class, cascade={"persist"})
* #Groups({"product_get"})
*/
private $idUserDelete;
/**
* Many products can have many products
* #ORM\ManyToMany(targetEntity=Product::class, mappedBy="myProducts")
*/
private $partOfthisProduct;
/**
* Many products can have many products
* #ORM\ManyToMany(targetEntity=Product::class, inversedBy="partOfthisProduct")
* #JoinTable(name="product_has_product",
* joinColumns={#JoinColumn(name="product_id", referencedColumnName="id")},
* inverseJoinColumns={#JoinColumn(name="related_product_id", referencedColumnName="id")}
* )
* #Groups({"product_get", "product_list"})
*/
private $myProducts;
/**
* #ORM\OneToMany(targetEntity=Sensor::class, mappedBy="product", cascade={"persist"})
* #Groups({"product_get", "product_list"})
* #ApiSubresource()
*/
private $sensors;
<?php
namespace App\Entity;
use ApiPlatform\Core\Annotation\ApiResource;
use ApiPlatform\Core\Annotation\ApiSubresource;
use App\Repository\ProductModelRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\Mapping\ManyToMany;
use Symfony\Component\Serializer\Annotation\Groups;
use Doctrine\ORM\Mapping\JoinTable;
use Doctrine\ORM\Mapping\JoinColumn;
/**
* #ORM\Entity(repositoryClass=ProductModelRepository::class)
* #ApiResource(
* itemOperations={"get"},
* collectionOperations={"get"},
* normalizationContext={
* "groups"={"read"}}
* )
*/
class ProductModel
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
* #Groups({"read", "product_get", "product_list"})
*/
private $id;
/**
* #ORM\Column(type="string", length=50)
* #Groups({"read", "product_get", "product_list"})
*/
private $modelName;
/**
* #ORM\ManyToOne(targetEntity=ProductType::class, cascade={"persist"})
* #ORM\JoinColumn(nullable=false)
* #Groups({"read", "product_get", "product_list"})
*/
private $idProductType;
/**
* #ORM\ManyToOne(targetEntity=Unit::class)
*/
private $idInputUnit;
/**
* #ORM\ManyToOne(targetEntity=Unit::class)
*/
private $idOutputUnit;
/**
* #ORM\ManyToOne(targetEntity=Brand::class, cascade={"persist"})
* #ORM\JoinColumn(nullable=false)
* #Groups({"read", "sensor_get", "product_list"})
*/
private $idBrand;
/**
* #ORM\ManyToMany(targetEntity=TestType::class)
* #Groups({"read", "sensor_get", "product_get"})
*/
private $idTestsTypes;
/**
* #ORM\Column(type="integer", nullable=true)
* #Groups({"read", "sensor_get"})
*/
private $periodicity;
/**
* #ORM\Column(type="float", nullable=true)
* #Groups({"read", "sensor_get", "product_get"})
*/
private $nominalSensitivity;
/**
* #ORM\ManyToOne(targetEntity=TestType::class)
* #Groups({"read", "sensor_get", "product_get"})
*/
private $periodicityTest;
/**
* Many ProductModel have Many SensorModel.
* #ManyToMany(targetEntity="SensorModel")
* #JoinTable(name="productModel_sensorModels",
* joinColumns={#JoinColumn(name="Product_model_id", referencedColumnName="id")},
* inverseJoinColumns={#JoinColumn(name="Sensor_Model_id", referencedColumnName="id", unique=true)}
* )
* #Groups({"read", "sensor_get", "product_get"})
*/
private $sensorModels;
What would be the way to do this ? Thank you for your help.
Think the best way to do it is with a custom action that calls a method from the entity's repository.
First you add a custom operation to your #ApiResource definition, in the collectionOperations part in this case.
/**
* #ApiResource(
* itemOperations={"get","put","delete"},
* collectionOperations={
* "get","post",
* "types"={
* "method"="GET",
* "path"="/product_models/brands",
* "controller"=DistinctBrandsAction::class,
* "openapi_context"={
* "parameters"={}
* },
* "read"=false,
* }
* }
* )
* #ORM\Entity(repositoryClass=Repository::class)
*/
Then you add a method to your entity's repository (it would be ProductModelRepository in your case).
This method will query the collection and get the distinct values of the desired column. You'll have to modify this a bit to get the exact output you want (add the product types etc.):
//..blah blah.. use statements etc.
class ProductModelRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Report::class);
}
//this is the method you're adding:
//for symfony 3+ you use groupBy() instead of distinct() to get distinct values for a column
public function getDistinctBrands() {
return $this->createQueryBuilder('r')
->select('r.idBrand')
->groupBy('r.idBrand')
->getQuery()
->getResult();
}
}
Then you need to create a controller for your configured action that calls the method you added to the repository and then outputs it. (This would go in src/Controller/Action/DistinctBrandsAction.php if you're using autowiring)
<?php
namespace App\Controller\Action;
use App\Entity\Report;
use App\Repository\ProductModelRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
/**
* Class DistinctBrandsAction
*/
final class DistinctBrandsAction extends AbstractController
{
/**
* #param ProductModelRepository $productRepository
* #return Array
*/
public function __invoke(ProductModelRepository $productRepository): Array
{
return $productRepository->getDistinctBrands();
}
}
You can use the console to see what your resulting route is. It should be grouped with your ProductModel routes when running php bin/console debug:router
Further reading:
https://api-platform.com/docs/core/pagination/#custom-controller-action

Error: Cannot select entity through identification variables without choosing at least one root entity alias

I'm using this query builder in my repository:
public function findByCityCategory($city, $category)
{
$qb = $this->createQueryBuilder('e')
->select(['e.id','e.title','e.address', 'e.lat', 'e.lng', 'e.siteUrl', 'e.phoneNo', 'w', 'd.id as category', 'avg(r.rating) as rating'])
->innerJoin('e.workingTimes', 'w')
->innerJoin('e.category', 'd')
->where('d.id = :categoryId')
->andWhere('e.city = :cityId')
->leftJoin('e.ratings', 'r')
->groupBy('r.place')
->setParameter('categoryId', $category)
->setParameter('cityId', $city);
return $qb->getQuery()->getResult();
}
But when I try to execute it, I get:
"message": "[Semantical Error] line 0, col -1 near 'SELECT e.id,': Error: Cannot select entity through identification variables without choosing at least one root entity alias.",
"class": "Doctrine\\ORM\\Query\\QueryException",
I looked for similar problems here and here but none of these worked for me. My Entities looks like that:
<?php
namespace AppBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Place
*
* #ORM\Table(name="place")
* #ORM\Entity(repositoryClass="AppBundle\Repository\PlaceRepository")
*/
class Place
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
* #Assert\NotBlank()
* #ORM\Column(name="title", type="string", length=255)
*/
private $title;
/**
* #var string
* #Assert\NotBlank()
* #ORM\Column(name="address", type="string", length=255)
*/
private $address;
/**
* #var float
* #Assert\NotBlank()
* #ORM\Column(name="lat", type="float")
*/
private $lat;
/**
* #var float
* #Assert\NotBlank()
* #ORM\Column(name="lng", type="float")
*/
private $lng;
/**
* #var string
*
* #ORM\Column(name="description", type="text", nullable=true)
*/
private $description;
/**
* #var string
*
* #ORM\Column(name="fb_page", type="string", length=255, nullable=true)
*/
private $fbPage;
/**
* #Assert\NotBlank()
* #ORM\ManyToOne(targetEntity="City")
* #ORM\JoinColumn(name="city_id", referencedColumnName="id")
*/
private $city;
/**
* #Assert\NotBlank()
* #ORM\ManyToOne(targetEntity="Category", inversedBy="places")
* #ORM\JoinColumn(name="category_id", referencedColumnName="id")
*/
private $category;
/**
* #var string
*
* #ORM\Column(name="site_url", type="string", length=255, nullable=true)
*/
private $siteUrl;
/**
* #ORM\ManyToMany(targetEntity="WorkingTime", cascade={"persist"})
* #ORM\JoinTable(name="places_workingtimes",
* joinColumns={#ORM\JoinColumn(name="place_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="workingtime_id", referencedColumnName="id", unique=true)}
* )
*/
private $workingTimes;
/**
* #var string
* #ORM\Column(name="phone_no", type="string", length=255, nullable=true)
*
*/
private $phoneNo;
/**
* #ORM\OneToMany(targetEntity="Rating", mappedBy="place")
*/
private $ratings;
}
`
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Rating
*
* #ORM\Table(name="rating")
* #ORM\Entity(repositoryClass="AppBundle\Repository\RatingRepository")
*/
class Rating
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var int
*
* #ORM\Column(name="rating", type="smallint")
*/
private $rating;
/**
* #ORM\ManyToOne(targetEntity="Place", inversedBy="ratings")
* #ORM\JoinColumn(name="place_id", referencedColumnName="id")
*/
private $place;
/**
* #ORM\ManyToOne(targetEntity="User")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
private $user;
This error only occurs, when I try to select 'w'. So, how can I join this collection of objects?
If you want to only get partial fields from your entity, you have to use the PARTIAL keyword as explained on documentation: http://doctrine-orm.readthedocs.org/projects/doctrine-orm/en/latest/reference/partial-objects.html
It would be better to load all the fields instead of some if you use the ORM query builder, because the ORM is made to work with objects. If you need only few fields, it can be a better practice to use the native SQL query builder.
I've managed to do it by excluding unnecessary fields from Place entity using JMS Serializer's Exclude() annotation instead of selecting required fields from entity.

Can't Create association on Symfony2

I'm trying to create a "OneToMany" bidirectional association in my project but when I execute "doctrine:schema:update" nothing happens.
If I create this association directly from Sequel Pro and run the update schema command, that changes dissapear... :/
The relations is:
- One "id" from Customers Table with many "customer_id" form Control table.
Here is the Customers code:
<?php
namespace Ourentec\CustomersBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* Customers
*
* #ORM\Table()
* #ORM\Entity
*/
class Customers
{
/* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=100)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="lastname", type="string", length=100)
*/
private $lastname;
/**
* #var string
*
* #ORM\Column(name="address", type="text")
*/
private $address;
/**
* #var string
*
* #ORM\Column(name="phone", type="string", length=100)
*/
private $phone;
/**
* #var string
*
* #ORM\Column(name="pass", type="string", length=100)
*/
private $pass;
/**
* #var string
*
* #ORM\Column(name="tasks", type="text")
*/
private $tasks;
/**
* #var string
*
* #ORM\Column(name="status", type="string", length=100)
*/
private $status;
/**
* #var string
*
* #ORM\Column(name="email", type="string", length=100)
*/
private $email;
/**
* #var \DateTime
*
* #ORM\Column(name="date", type="datetime")
*/
private $date;
/**
* #var string
*
* #ORM\Column(name="location", type="string", length=100)
*/
private $location;
/**
* #ORM\OneToMany(targetEntity="Control", mappedBy="customers")
*/
private $customer_id;
public function __construct()
{
$this->customer_id = new ArrayCollection();
}
And the Control code:
<?php
namespace Ourentec\CustomersBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Control
*
* #ORM\Table()
* #ORM\Entity
*/
class Control
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var integer
*
* #ORM\Column(name="customer_id", type="integer")
*
* #ORM\ManyToOne(targetEntity="Customers", inversedBy="control")
* #ORM\JoinColumn(name="customer_id", referencedColumnName="id")
*/
private $customerId;
/**
* #var integer
*
* #ORM\Column(name="user_id", type="integer")
*/
private $userId;
/**
* #var \DateTime
*
* #ORM\Column(name="date", type="datetime")
*/
private $date;
/**
* #var integer
*
* #ORM\Column(name="seen", type="smallint")
*/
private $seen;
I followed the documentation from this 2 websites
http://symfony.com/doc/current/book/doctrine.html
http://librosweb.es/libro/symfony_2_x/capitulo_8/relaciones_y_asociaciones_de_entidades.html
But I don't know why it does not work..
Any idea will be appreciated :)
Mapping are not correct, I will try to explain how it works.
In Customers entity (you should rename it to Customer, entites names are singular)
/**
* #ORM\OneToMany(targetEntity="Control", mappedBy="customer")
*/
private $controls;
Mapped by option defines field name in the other entity.
/**
* #var integer
*
* #ORM\Column(name="customer_id", type="integer")
*
* #ORM\ManyToOne(targetEntity="Customers", inversedBy="controls")
* #ORM\JoinColumn(name="customer_id", referencedColumnName="id")
*/
private $customer;
Same thing with inversedBy.
In Customers entity you also need to init controls var as an ArrayCollection:
public function __construct()
{
$this->controls = new ArrayCollection();
}
With these mappings schema should be updated correctly.
For more info, check doctrine docs.

Many-To-Many relationship Doctrine

I have had quite a few problems with my current entities mapping, so I wanted an opinion on what is the issue with it.
Let's say with have the following tables example with Doctrine, but also keep in mind that a Group can have many Users, and a User can be part of many Groups
User
--
id
name
Group
--
id
title
User Groups
--
id
user_id
group_id
And this is my current approach:
/**
* User
*
* #ORM\Table(name="user")
* #ORM\Entity(repositoryClass="SomeBundle\Entity\Repository\UserRepository")
*/
class User
{
/**
* #var integer
* #ORM\Id
* #ORM\Column(name="user_id", type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $user_id;
// some other fields and functions here
}
Group
/**
* Group
*
* #ORM\Table(name="group", indexes={#ORM\Index(name="group_parent", columns={"parent_id"})})
* #ORM\Entity(repositoryClass="SomeBundle\Entity\Repository\GroupRepository")
*/
class Group
{
/**
* #var integer
*
* #ORM\Column(name="category_id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $categoryId;
// some other functions and variables here
}
...and user_groups
/**
* User_Groups
*
* #ORM\Table(name="user_groups",
* indexes={
* #ORM\Index(name="user_group_user", columns={"user_id"}),
* #ORM\Index(name="user_group_group", columns={"group_id"})
* }
* )
* #ORM\Entity(repositoryClass="SomeBundle\Entity\Repository\UserGroupRepository")
*/
class UserGroup
{
/**
* #var integer
*
* #ORM\Id
* #ORM\Column(name="user_group_id", type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $userGroupId;
/**
* #var \SomeBundle\Entity\User
* #ORM\Column(name="user_id")
*
* #ORM\ManyToMany(targetEntity="SomeBundle\Entity\User", inversedBy="userGroups")
* #ORM\JoinTable(name="users",
* joinColumns={#ORM\JoinColumn(name="user_id", referencedColumnName="userId")})
*/
private $user;
/**
* #var SomeBundle\Entity\Category
*
* #ORM\ManyToOne(targetEntity="SomeBundle\Entity\Group", inversedBy="groups")
* #ORM\JoinColumn(name="group_id", referencedColumnName="group_id")
*
*/
private $group;
/// etc
}
Any help would be appreciated!
/** #Entity **/
class User
{
// ...
/**
* #ManyToMany(targetEntity="Group", inversedBy="users")
* #JoinTable(name="users_groups")
**/
private $groups;
public function __construct() {
$this->groups = new \Doctrine\Common\Collections\ArrayCollection();
}
// ...
}
/** #Entity **/
class Group
{
// ...
/**
* #ManyToMany(targetEntity="User", mappedBy="groups")
**/
private $users;
public function __construct() {
$this->users = new \Doctrine\Common\Collections\ArrayCollection();
}
// ...
}
Your case is Many-to-Many, Bidirectional Association
Doctrine association mapping
In this example, I have a product and a mesureUnit they relate many to many.
In your case you only need user and group. The UserGroups is generated automatically.
Many to many relationship are done as follows:
<?php
namespace TeamERP\StoresBundle\Entity;
use Doctrine\ORM\Mapping AS ORM;
/**
* #ORM\Entity
*/
class MesureUnit
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(type="string", length=100, nullable=true)
*/
private $name;
/**
* #ORM\Column(type="string", length=10, nullable=true)
*/
private $abreviation;
/**
* #ORM\OneToMany(targetEntity="TeamERP\StoresBundle\Entity\ProductActivity", mappedBy="mesureUnit")
*/
private $pproductActivity;
/**
* #ORM\ManyToMany(targetEntity="TeamERP\StoresBundle\Entity\Product", mappedBy="mesureUnit")
*/
private $product;
/**
* Constructor
*/
public function __construct()
{
$this->pproductActivity = new \Doctrine\Common\Collections\ArrayCollection();
$this->product = new \Doctrine\Common\Collections\ArrayCollection();
}
Then the produc class could be like:
<?php
namespace TeamERP\StoresBundle\Entity;
use Doctrine\ORM\Mapping AS ORM;
/**
* #ORM\Entity
*/
class Product
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(type="string", length=50, nullable=true)
*/
private $code;
/**
* #ORM\Column(type="string", length=250, nullable=true)
*/
private $description;
/**
* #ORM\Column(type="datetime", nullable=true)
*/
private $date_received;
/**
* #ORM\OneToMany(targetEntity="TeamERP\StoresBundle\Entity\ProductActivity", mappedBy="product")
*/
private $pproductActivity;
/**
* #ORM\ManyToOne(targetEntity="TeamERP\StoresBundle\Entity\Category", inversedBy="product")
* #ORM\JoinColumn(name="category_id", referencedColumnName="id")
*/
private $category;
/**
* #ORM\ManyToOne(targetEntity="TeamERP\StoresBundle\Entity\AJob", inversedBy="product")
* #ORM\JoinColumn(name="job_id", referencedColumnName="id")
*/
private $aJob;
/**
* #ORM\ManyToMany(targetEntity="TeamERP\StoresBundle\Entity\MesureUnit", inversedBy="product")
* #ORM\JoinTable(
* name="MesureUnit2Product",
* joinColumns={#ORM\JoinColumn(name="product_id", referencedColumnName="id", nullable=false)},
* inverseJoinColumns={#ORM\JoinColumn(name="mesure_unit_id", referencedColumnName="id", nullable=false)}
* )
*/
private $mesureUnit;
/**
* Constructor
*/
public function __construct()
{
$this->pproductActivity = new \Doctrine\Common\Collections\ArrayCollection();
$this->mesureUnit = new \Doctrine\Common\Collections\ArrayCollection();
}
Yo do not need to create the table manually. It is generated by Doctrine.
Hope it helps

symfony2 how to get mapping table id?

how to get mapping table id from mappipng table?
i have user and group table mapped together
and i want to get group id at login time but i am not getting it.
i have three table
user, group, user_groupname
->first table
user
id,name
->second table
group
id,name
->third table
groupname
user_id,group_id
first entity is as follows
/Entity/groupname.php
class groupname
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255, nullable=false)
*/
private $name;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="role", inversedBy="groupname")
* #ORM\JoinTable(name="groupname_role",
* joinColumns={
* #ORM\JoinColumn(name="groupname_id", referencedColumnName="id")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="role_id", referencedColumnName="id")
* }
* )
*/
private $role;
/**
* #ORM\ManyToMany(targetEntity="\Dashboard\SecurityBundle\Entity\User", mappedBy="groupname")
*/
private $users;
}
second entity is as follows
/Entity/User.php
<?php
namespace Dashboard\SecurityBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\AdvancedUserInterface;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Dashboard\SecurityBundle\Entity\User
*
* #ORM\Table(name="users")
* #ORM\Entity(repositoryClass="Dashboard\SecurityBundle\Repository\UserRepository")
* #ORM\HasLifecycleCallbacks()
*/
class User implements UserInterface, \Serializable, AdvancedUserInterface
{
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(type="string", length=25, unique=true)
*/
protected $username;
*/
/**
* #ORM\ManyToMany(targetEntity="\Dashboard\AdminManageUserBundle\Entity\groupname", inversedBy="users")
*
*/
public $groupname;
/**
* #var Dashboard\SecurityBundle\Entity\UserPhoto UserPhoto
*
*/
private $userPhoto;
public function __construct()
{
$this->groupname = new ArrayCollection();
}
/**
* Add groupname
*
* #param \Dashboard\AdminManageUserBundle\Entity\groupname $groupname
* #return User
*/
public function addGroupname(\Dashboard\AdminManageUserBundle\Entity\groupname $groupname)
{
$this->groupname[] = $groupname;
return $this;
}
/**
* Remove groupname
*
* #param \Dashboard\AdminManageUserBundle\Entity\groupname $groupname
*/
public function removeGroupname(\Dashboard\AdminManageUserBundle\Entity\groupname $groupname)
{
$this->groupname->removeElement($groupname);
}
/**
* Get groupname
*
* #return \Doctrine\Common\Collections\ArrayCollection
*/
public function getGroupname()
{
return $this->groupname;
}
}
and i have following code right in Controller file
$userEntity = $this->getDoctrine()->getRepository('DashboardSecurityBundle:User')->findOneBy(array('username' =>$usernames));
and i have print_R($userEntity) pc got hanged
$userEntiry is a object of UserEntity
So, your pc got hanged.
please try this.
print_r($userEntity->getUsername());

Categories