How can I fetch rows using Docrine2 in a ManytoOne relationship - php

I have the following tables, where I have no problem in inserting, updating etc. But, how can I fetch the result rows for this kind of mapping?
Organizations
-->id
-->name
users
-->id
-->first_name
doctors
-->id
-->user_id
org_doctors
-->id
-->org_id
-->doctor_id
This is my OrgDoctor Entity:
<?php
namespace Doctor\Entity;
use Doctrine\ORM\Mapping as ORM;
use Library\Entity\BaseEntity;
use User\Entity\User;
use Doctor\Entity\Doctor;
use Organization\Entity\Organization;
/**
* #ORM\Entity
* #ORM\Table(name="org_doctors")
*/
class OrgDoctor extends BaseEntity{
/**
* #ORM\ManyToOne(targetEntity="Doctor\Entity\Doctor", inversedBy="orgDoctor")
* #ORM\JoinColumn(name="doctor_id",referencedColumnName="id",nullable=false)
*/
protected $doctor;
/**
* #ORM\ManyToOne(targetEntity="Organization\Entity\Organization", inversedBy="orgDoctor")
* #ORM\JoinColumn(name="org_id", referencedColumnName="id", nullable=false)
*/
protected $organization;
public function setDoctor(Doctor $doctor = null)
{
$this->doctor = $doctor;
return $this;
}
public function getDoctor()
{
return $this->doctor;
}
public function setOrganization(Organization $organization = null)
{
$this->organization = $organization;
return $this;
}
public function getOrganization()
{
return $this->organization;
}
}
And this is my Doctor Entity:
<?php
namespace Doctor\Entity;
use Library\Entity\BaseEntity;
use Users\Entity\User;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="doctors")
*/
class Doctor extends BaseEntity {
/**
* #ORM\OneToOne(targetEntity="Users\Entity\User")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false)
* #var Users\Entity\User
*/
private $user;
/**
* #ORM\Column(name="summary", type="string")
* #var string
*/
private $summary;
function getUser() {
return $this->user;
}
function setUser(User $user) {
$this->user = $user;
}
function getSummary() {
return $this->summary;
}
function setSummary($summary) {
$this->summary = $summary;
}
}
This is how I'm fetching the result for a single doctor:
$doctor = $this->entityManager->find('Doctor\Entity\Doctor', (int) $doctorId);
How can I fetch rows from the OrgDoctor entity?
this is how i tried using queryBuilder:
$qb = $this->entityManager->createQueryBuilder();
$qb->select('od', 'd', 'o')
->from('Doctor\Entity\OrgDoctor', 'od')
->join('od.organization', 'o')
->join('od.doctor', 'd')
->where('od.organization = :organization')
->setParameter('organization', $orgId);
$query = $qb->getQuery();
$results = $query->getResult();
var_dump($results);
Notice: Undefined index: orgDoctor in C:\xampp\htdocs\corporate-wellness\vendor\doctrine\orm\lib\Doctrine\ORM\Internal\Hydration\ObjectHydrator.php on line 125
In Organization Entity:
/**
* #ORM\OneToMany(targetEntity="Doctor\Entity\OrgDoctor", mappedBy="organization")
*/
protected $orgDoctor;

Given your entity mapping, Doctrine should provide you with an out of the box repository for your OrgDoctor entity. That repository implements a few methods for you to retrieve entities of that type. One of them is findBy, which return arrays of OrgDoctor entities:
$this->getEntityManager()->getRepository(OrgDoctor::class)->findBy(['doctor' => $doctorId]));
$this->getEntityManager()->getRepository(OrgDoctor::class)->findBy(['organization' => $organizationId]));
$this->getEntityManager()->getRepository(OrgDoctor::class)->findBy(['doctor' => $doctorId, 'organization' => $organizationId]));
The last example, would be quite similar to findOneBy, which would return an OrgDoctor entity instead of an array:
$this->getEntityManager()->getRepository(OrgDoctor::class)->findOneBy(['doctor' => $doctorId, 'organization' => $organizationId]));
If you're planning to loop through the results and access their properties or other relationships, you might want to change the default repository strategy and define a custom repository for your OrgDoctor entity. What this will allow you to do, is to write your custom queries for retrieving your entities by means of a query builder class and DQL.
In order to avoid N+1 problems, you want to fetch join before a loop to fetch all the necessary associations in one go, so you won't be running N queries within your loop:
$qb->select('od', 'd', 'o')
->from(OrgDoctor::class, 'od')
->join('od.organization', 'o')
->join('od.doctor', 'd')
->where('od.doctor = :doctor')
->setParameter('doctor', $doctorId)
;

Related

Symfony - Building query for table created by many to many relation

I have 2 entities connected with many to many relation into a 3th table, and I want to get every color for an id of product:
/**
* #var ArrayCollection
*
* #ORM\ManyToMany(targetEntity="AppBundle\Entity\Color", inversedBy="products")
* #ORM\JoinTable(name="products_colors",
* joinColumns={#ORM\JoinColumn(name="product_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="color_id", referencedColumnName="id")}
* )
*/
private $colors;
And in my second entity:
/**
* #var ArrayCollection
*
* #ORM\ManyToMany(targetEntity="AppBundle\Entity\Product", mappedBy="colors")
*/
private $products;
This is my query: (I was trying to make some joins but cant make it work)
class ProductRepository extends \Doctrine\ORM\EntityRepository
{
public function getColors($id)
{
$query = $this->createQueryBuilder('p')
->join('AppBundle\Entity\Color', 'c')
->where('c.product_id = :id')
->setParameter('id', $id)
->getQuery()
->getResult();
return $query;
}
}
I got this error:
[Semantical Error] line 0, col 85 near 'product_id =': Error: Class
AppBundle\Entity\Color has no field or association named product_id
which I understand, but can't think of a way to make this work.
Symfony expects you to reference the entity (not id) of an object when mapped by ManyToMany relationship. Try:
class ProductRepository extends \Doctrine\ORM\EntityRepository
{
public function getColors(Product $product)
{
$query = $this->createQueryBuilder('p')
->join('AppBundle\Entity\Color', 'c')
->where('c.product = :product')
->setParameter('product', $product)
->getQuery()
->getResult();
return $query;
}
}
Of course you'll have to modify your call to this function accordingly.
You can also skip the query creation altogether with the getter function in your entity; symfony automagically will do the query for you.
// class Product
private $colors; // as you have it set up already
/**
* #return ArrayCollection|Color[]
*/
public function getColors()
{
return $this->colors;
}

Symfony 3 FOS Rest + JMS Serializer groups

My composer.json (part of it):
{
"require": {
"symfony/symfony": "3.1.*",
"jms/serializer-bundle": "^1.1",
"friendsofsymfony/rest-bundle": "^2.1"
}
}
I have some entities which I'd like to return partial data for the list action and complete for the find action. For so, I have these files:
Product.php
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use JMS\Serializer\Annotation as JMS;
/**
* #ORM\Entity
* #ORM\Table(name="represented")
* #JMS\ExclusionPolicy("ALL")
*/
class Product
{
/**
* #var integer
* #ORM\Column(type="integer", nullable=false, options={"unsigned"=true})
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
* #ORM\Column(type="string", nullable=false, length=48)
*/
protected $name;
/**
* #var Group
* #ORM\ManyToOne(targetEntity="Group", inversedBy="products")
* #ORM\JoinColumn(name="group_id", referencedColumnName="id")
*/
protected $group;
public function getId()
{
return $this->id;
}
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
public function setGroup(Group $group)
{
$this->group = $group;
}
public function getGroup()
{
return $this->group;
}
}
ProductController.php
<?php
namespace AppBundle\Controller;
use FOS\RestBundle\Controller\Annotations\Get;
use FOS\RestBundle\Controller\FOSRestController;
use AppBundle\Entity\Product;
class ProductController extends FOSRestController
{
/**
* #Get("/product", name="list_products")
*/
public function listAction()
{
$products = $this->getDoctrine()
->getRepository('AppBundle:Product')
->findBy([], [ 'name' => 'ASC' ]);
$view = $this->view($products);
return $this->handleView($view);
}
/**
* #Get("/product/{id}", requirements={"id" = "\d+"}, name="get_product")
*/
public function getAction($id)
{
$em = $this->getDoctrine()->getManager();
$product = $em->getRepository('AppBundle:Product')
->find($id);
if ( ! $product) {
$error = [
'error' => 'Product not found'
];
$view = $this->view($error, 404);
} else {
$view = $this->view($product);
}
return $this->handleView($view);
}
}
I would like to be able to not show the group property on the list result. For this I have tried a few of approaches, mainly with groups.
Just use configure the group name for the properties I want to show
on my list with Groups({"List"}) and refer this group on the
controller with #View(serializerGroups={"List"}). But this had no
affect as all properties are visible.
Configure #ExclusionPolicy("all") for the entire entity didn't
work as well.
In addition to ExclusionPolicy, #Expose to all properties I wanted
to show in some or all groups, but that made all properties marked
to be shown.
I also tried some more variants of these, but nothing that change the results.
End of your controller action should not be only:
return $this->handleView($view);
But for getting a group or groups working you need to activate them. On top of the class you need to add FOSRest Context, not JMS context:
use FOS\RestBundle\Context\Context;
and in the controller actions before returning view:
$view = $this->view($products, 200);
$context = new Context();
$context->setGroups(['list']);
$view->setContext($context);
return $this->handleView($view);
This will work for Symfony 3.2 and FOSRest 2.1 and 2.0.
Link for upgrading documentation for FOSRest:
https://github.com/FriendsOfSymfony/FOSRestBundle/blob/master/UPGRADING-2.0.md
If you use #Exclude then this should work. Another option I have used is to make a small addition to config.yml:
fos_rest:
serializer:
groups: ['Default']
This requires that the entity properties be in the group Default in order to be serialized. If you have no #Groups annotation on a property then it will be in Default, but as soon as you add the #Groups annotation then it will no longer be in the Default group (unless you specifically add it.)
This allowed the default serialization process to include all the entity fields except for those with a #Groups annotation, and then elsewhere I could serialize with both Default and my other groups selected if I wanted everything to be included.
// Function in the Controller class
public function getAction(MyEntity $me) {
// Use automatic serializer, only things in 'Default' group are included
return $me;
}

join tables in doctrine2

I am trying join the tables, in Doctrine2 Query Builder. This was my query to join the two tables and get the result.
Initially i have two tables to be joined:
--> employees
--> org_employees
Other tables:
--> users
Here in my Doctrine2 Query builder code, i have joined 2 tables to fetch the results of particular Organization employees by passing the Organization id.
SELECT
*
FROM org_branch_employees oe
LEFT JOIN employees e ON oe.employee_id = e.id
WHERE
oe.org_id = 1;
By using the Query Builder the above sql code has been changed like below.
$qb = $this->entityManager->createQueryBuilder();
$qb->select('oe', 'e', 'o')
->from('Employee\Entity\OrgEmployee', 'oe')
->leftJoin('oe.organization', 'o')
->leftJoin('oe.employee', 'e')
->where('oe.organization = :organizationId')
->setParameter('organizationId', $orgId);
$query = $qb->getQuery();
$orgEmployees = $query->getResult();
return $orgEmployees;
This is my Employee Entity:
<?php
namespace Employee\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Library\Entity\BaseEntity;
use Users\Entity\User;
use Organization\Entity\Organization;
//use Organization\Entity\OrgEmployee;
/**
* Description of Employee
*
* #author Macwin
*/
/**
* #ORM\Entity
* #ORM\Table(name="employees")
*/
class Employee extends BaseEntity {
/**
* #ORM\OneToOne(
* targetEntity="Users\Entity\User"
* )
* #ORM\JoinColumn(
* name="user_id",
* referencedColumnName="id",
* nullable=false
* )
*/
private $user;
/**
* #ORM\Column(name="employee_code", type="string", nullable=true)
* #var string
*/
protected $empCode;
/**
* #ORM\OneToOne(
* targetEntity="Organization\Entity\Organization"
* )
* #ORM\JoinColumn(
* name="org_id",
* referencedColumnName="id",
* nullable=false
* )
*/
private $organization;
/**
* #ORM\OneToMany(targetEntity="Employee\Entity\OrgEmployee", mappedBy="employee")
*/
protected $orgEmployee;
/**
* #ORM\OneToMany(targetEntity="Employee\Entity\OrgEmployeeDesignation", mappedBy="employee")
*/
protected $orgEmployeeDesignation;
public function __construct() {
$this->organizations = new \Doctrine\Common\Collections\ArrayCollection();
parent::__construct();
}
public function getOrganizations() {
return $this->organizations;
}
public function addOrganization(Organization $organization = null) {
$this->organizations->add($organization);
}
public function setUser(User $user = null) {
$this->user = $user;
}
public function getUser() {
return $this->user;
}
public function getEmpCode() {
return $this->empCode;
}
public function setEmpCode($empCode) {
$this->empCode = $empCode;
}
public function setOrganization(Organization $organization = null) {
$this->organization = $organization;
}
public function getOrganization() {
return $this->organization;
}
function getOrgEmployeeDesignation() {
return $this->orgEmployeeDesignation;
}
function setOrgEmployeeDesignation($orgEmployeeDesignation) {
$this->orgEmployeeDesignation = $orgEmployeeDesignation;
}
public function getOrgEmployee() {
return $this->orgEmployee;
}
public function __toString() {
return __CLASS__ . ": [id: {$this->id}, name: {$this->name}]";
}
}
Here is my OrgEmployee Entity Which maps the Organization table and Enity table, to get the Organization details and Employee Details.
<?php
namespace Employee\Entity;
use Doctrine\ORM\Mapping as ORM;
use Library\Entity\BaseEntity;
use Employee\Entity\Employee;
use Organization\Entity\Organization;
/**
* Description of Org Employees
*
* #author Macwin
*/
/**
* #ORM\Entity
* #ORM\Table(name="org_branch_employees")
*/
class OrgEmployee extends BaseEntity{
/**
* #ORM\ManyToOne(targetEntity="Employee\Entity\Employee", inversedBy="orgEmployee")
* #ORM\JoinColumn(name="employee_id",referencedColumnName="id",nullable=false)
*/
protected $employee;
/**
* #ORM\ManyToOne(targetEntity="Organization\Entity\Organization", inversedBy="orgEmployee")
* #ORM\JoinColumn(name="org_branch_id", referencedColumnName="id", nullable=false)
*/
protected $organization;
public function setEmployee(Employee $employee = null)
{
$this->employee = $employee;
return $this;
}
public function getEmployee()
{
return $this->employee;
}
public function setOrganization(Organization $organization = null)
{
$this->organization = $organization;
return $this;
}
public function getOrganization()
{
return $this->organization;
}
}
Here is how i am getting the Organization details and Employee Details:
'employeeCode' => $orgEmp->getEmployee()->getEmpCode(),
userFirstName = $orgEmp->getEmployee()->getUser()->getFirstName(),
Being, employees table has mapping of users table, i can fetch the users information,
so far so good, but while i am trying to join more tables here, i couldnt bring the exact result.
But when i need to make the filter in the above functionality, i am not sure, how can bring the exact result.
Like filter by employee_code, user first name.
Can anyone guide me to bring the result. I am working on the REST API side to give the result to the client. Pagination was also there in the functionality.
I am trying the following if i am rightly said:
SELECT
*
FROM org_branch_employees oe
LEFT JOIN employees e ON oe.employee_id = e.id
LEFT JOIN users u ON e.user_id = u.id
WHERE
oe.org_id = 1 AND
u.user_first_name = "John" and
e.employee_code = "EMP777"
So the first query is working as needed? You just need to join the user entity and add some where conditions? Or maybe I misunderstood the problem.
$qb = $this->entityManager->createQueryBuilder();
$qb->select('oe', 'e', 'o', 'user')
->from('Employee\Entity\OrgEmployee', 'oe')
->leftJoin('oe.organization', 'o')
->leftJoin('oe.employee', 'e')
->leftJoin('e.user','user')
->andWhere('oe.organization = :organizationId')
->setParameter('organizationId', $orgId),
->andWhere('user.user_first_name = :userFirstName')
->setParameter('userFirstName', 'John'),
->andWhere('e.employee_code = :employeeCode')
->setParameter('employeeCode', 'Emp666');
return $qb->getQuery()->getResult();

How can I get an entity from Doctrine Fixture reference?

I have added data fixtures in my project that relies on referencing entity objects from each other.
In data fixture one, I have added entity references such as:
// GroupEntity_Fixtures.php file
$this->addReference('GROUP_USER', $groupUser);
$this->addReference('GROUP_ADMIN', $groupAdmin);
Where $groupAdmin and $groupUser are both Group() entities. In my second fixtures file I want to add those entities to my User entity via:
//UserEntity_Fixtures.php file
$userActive->addGroup($this->getReference('GROUP_USER'));
$userActive is a User entity with a Many to Many relationship to Group Entity. Unfortunately it seems that I am only passing in a proxy of the entity and not the entity itself which renders the following error:
[Symfony\Component\Debug\Exception\ContextErrorException]
Catchable Fatal Error: Argument 1 passed to Blogger\BlogBundle\Entity\User:
:addGroup() must be an instance of Blogger\BlogBundle\Entity\groups, instan
ce of Proxies\__CG__\Blogger\BlogBundle\Entity\Group given, called in /home
/na/Practice/src/Blogger/BlogBundle/DataFixtures/ORM/CreateUserController_S
ignUpForm_UserEntity_Fixtures.php on line 27 and defined in /home/na/Practi
ce/src/Blogger/BlogBundle/Entity/User.php line 305
How do I convert the reference from a proxy to the entity it expects?
Code for Group Fixture:
<?php
// DataFixtures/ORM/GroupEntity_Fixtrues.php
namespace Blogger\BlogBundle\DataFixtures\ORM;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\Persistence\ObjectManager;
use Blogger\BlogBundle\Entity\User;
use Blogger\BlogBundle\Entity\Group;
class GroupEntity_Fixtures extends AbstractFixture implements OrderedFixtureInterface
{
/**
* {#inheritDoc}
*/
public function load(ObjectManager $manager)
{
$groupUser = new Group();
$groupUser->setName('GROUP_USER');
$groupUser->setRole('ROLE_USER');
$manager->persist($groupUser);
$groupAdmin = new Group();
$groupAdmin->setName('GROUP_ADMIN');
$groupAdmin->setRole('ROLE_USER,ROLE_ADMIN');
$manager->persist($groupAdmin);
$manager->flush();
$this->addReference('GROUP_USER', $groupUser);
$this->addReference('GROUP_ADMIN', $groupAdmin);
}
public function getOrder()
{
return 1;
}
}
Code for User Fixture
<?php
// DataFixtures/ORM/CreateUserController_SignUpForm_UserEntity_Fixtrues.php
namespace Blogger\BlogBundle\DataFixtures\ORM;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\Persistence\ObjectManager;
use Blogger\BlogBundle\Entity\User;
use Blogger\BlogBundle\Entity\Group;
class CreateUserController_SignUpForm_UserEntity_Fixtures extends AbstractFixture implements OrderedFixtureInterface
{
/**
* {#inheritDoc}
*/
public function load(ObjectManager $manager)
{
$groupUser2 = new Group();
$groupUser2->setName('GROUP_USER');
$groupUser2->setRole('ROLE_USER');
$manager->persist($groupUser2);
// This person represents an active (email verified) user.
$userActive = new User();
$userActive->setPassword("passwordActive");
$userActive->setEmail("testActive#test.com");
$userActive->setUserName("testActive");
$userActive->setPassword(crypt($userActive->getPassword(),$userActive->getSalt()));
$userActive->setEmailToken(md5(uniqid(rand(), true)));
$userActive->addGroup($groupUser2);
//$userActive->getGroups()->add($groupRepository->getGroupByName("BASIC_USER"));
// This person represents an unactive (email not verified) user.
$userUnactive = new User();
$userUnactive->setPassword("passwordUnactive");
$userUnactive->setEmail("testUnactive#test.com");
$userUnactive->setUserName("testUnactive");
$userUnactive->setPassword(crypt($userUnactive->getPassword(),$userUnactive->getSalt()));
$userUnactive->setEmailToken(md5(uniqid(rand(), true)));
// Persist objects into the database
$manager->persist($userActive);
$manager->persist($userUnactive);
$manager->flush();
}
public function getOrder()
{
return 2;
}
}
Code for Group Entity:
/**
* #ORM\ManyToMany(targetEntity="User", inversedBy="groups")
*/
private $users;
Code for User Entity:
/**
* #ORM\ManyToMany(targetEntity="Group", mappedBy="users")
*/
protected $groups;
Added Group Methos:
/**
* Add groups
*
* #param \Blogger\BlogBundle\Entity\groups $groups
* #return User
*/
public function addGroup(\Blogger\BlogBundle\Entity\groups $groups)
{
$this->groups[] = $groups;
return $this;
}
The addGroup method has the wrong type hint:
It should be:
/**
* Add groups
*
* #param \Blogger\BlogBundle\Entity\Group $groups
* #return User
*/
public function addGroup(\Blogger\BlogBundle\Entity\Group $groups)
{
$this->groups[] = $groups;
return $this;
}
Notice \Blogger\BlogBundle\Entity\Group instead of \Blogger\BlogBundle\Entity\groups.

Symfony2 : Many-To-Many with a custom link table

I'm working on a form with 3 entities :
order (idorder)
support reference table (idsupport)
link table (idorder, idsupport)
And when i try to select one or more support i got this error:
Catchable Fatal Error: Argument 1 passed to Myapp\MyBundle\Entity\PcastCmdsupports::setIdsupports() must be an instance of Myapp\MyBundle\Entity\PcastSupports, instance of Doctrine\Common\Collections\ArrayCollection given,
called in C:\wamp\www\php\Symfony\vendor\symfony\src\Symfony\Component\Form\Util\PropertyPath.php on line 347 and defined in C:\wamp\www\php\Symfony\src\Myapp\MyBundle\Entity\PcastCmdsupports.php line 62
Since i already created my link table i saw on the web that i can simply create 2 Many-To-One relation in my link table :
/**
* #var PcastSupports
*
* #ORM\ManyToOne(targetEntity="PcastSupports")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="IDSUPPORTS", referencedColumnName="IDSUPPORTS")
* })
*/
private $idsupports;
/**
* #var PcastOrder
*
* #ORM\ManyToOne(targetEntity="PcastOrder")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="IDORDER", referencedColumnName="IDORDER")
* })
*/
private $idorder;
and my setters and getters :
/**
* Set idsupports
*
*/
public function setIdsupports(\Myapp\MyBundle\Entity\PcastSupports $idsupports)
{
$this->idsupports = $idsupports;
}
/**
* Get idsupports
*
*/
public function getIdsupports()
{
return $this->idsupports;
}
/**
* Set idorder
*
*/
public function setIdcommande(\Myapp\MyBundle\Entity\PcastOrder $idorder)
{
$this->idorder = $idorder;
}
/**
* Get idorder
*
*/
public function getIdorder()
{
return $this->idorder;
}
In my order form i can choose one or many supports so i created my form like this:
$form_clips = $this->createFormBuilder($cmdclips)
->add('idorder', new CmdsupportsType)
->getForm();
And finally my supportsType form:
$builder
->add('idsupports', 'entity', array(
'class' => 'MyappMyBundle:PcastSupports',
'property' => 'name',
'expanded' => true,
'multiple' => true,
'query_builder' => function(EntityRepository $er)
{
return $er->createQueryBuilder('pts')
->orderBy('pts.idsupports','ASC');
},
));
I'm not using any arraycollection so i don't understand the issue. And the issue happened during this action:
$form_clips->bindRequest($request);
Thank a lot for your help !
I tried to make it work with the many-to-many relation in a simple case (user, company and a user_company entities) but i got a problem when i try to add a company to a user:
Warning: oci_bind_by_name() [<a href='function.oci-bind-by-name'>function.oci-bind-by-name</a>]: Invalid variable used for bind in C:\wamp\www\php\Promocast\Symfony\vendor\doctrine-dbal\lib\Doctrine\DBAL\Driver\OCI8\OCI8Statement.php line 113
I googling a lot but i didn't find anything on this error... According to stack trace the error is when doctrine try to add the company object :
array('column' => ':param10', 'variable' => object(PcastCompany), 'type' => '1')
My user entity (societe = company):
/**
* #ORM\ManyToMany(targetEntity="PcastSociete", inversedBy="users")
* #ORM\JoinTable(name="PcastLienusersociete",
* joinColumns={#ORM\JoinColumn(name="ImUser_iduser", referencedColumnName="iduser")},
* inverseJoinColumns={#ORM\JoinColumn(name="PcastLienusersociete_idsociete", referencedColumnName="idsociete")}
* )
*/
private $societes;
public function getSocietes()
{
return $this->societes;
}
public function addSociete(\Myapp\MyBundle\Entity\PcastSociete $societe)
{
$this->societes[] = $societe;
}
My company entity:
/**
* #ORM\ManyToMany(targetEntity="ImUser", mappedBy="societes")
*/
private $users;
public function __construct() {
$this->users = new \Doctrine\Common\Collections\ArrayCollection();
}
If anybody have any idea...
Thanks
You should not have an entity representing the link table. If you annotate both your entities correctly, Doctrine will handle the creation of the link table by itself.
Moreover, you do not need any link table to do a Many-to-One relationship in the first place, what you want to do is use the Many-to-Many annotations in both entities.
http://readthedocs.org/docs/doctrine-orm/en/latest/reference/association-mapping.html?highlight=many%20to%20one#many-to-many-bidirectional
Start with the basics. I was curious about something else concerning ManyToMany so I grabbed your entities as a test case. Before diving into forms and such, make sure you can execute a simple test case from the command line such as:
use Zayso\ArbiterBundle\Entity\PcastSociete as Company;
use Zayso\ArbiterBundle\Entity\ImUser as User;
protected function test1()
{
$em = $this->getContainer()->get('doctrine.orm.entity_manager');
$company = new Company();
$em->persist($company);
$user = new User();
$user->addSociete($company);
$em->persist($user);
$em->flush();
}
For entities I used:
namespace Zayso\ArbiterBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Entity
*/
class ImUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer",name="iduser")
* #ORM\GeneratedValue
*/
protected $id;
public function getId() { return $this->id; }
/**
* #ORM\ManyToMany(targetEntity="PcastSociete", inversedBy="users")
* #ORM\JoinTable(name="PcastLienusersociete",
* joinColumns={#ORM\JoinColumn(name="ImUser_iduser", referencedColumnName="iduser")},
* inverseJoinColumns={#ORM\JoinColumn(name="PcastLienusersociete_idsociete", referencedColumnName="idsociete")}
* )
*/
private $societes;
public function getSocietes()
{
return $this->societes;
}
public function addSociete(PcastSociete $societe)
{
$this->societes[] = $societe;
}
public function __construct()
{
$this->societes = new ArrayCollection();
}
}
namespace Zayso\ArbiterBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Entity
*/
class PcastSociete
{
/**
* #ORM\Id
* #ORM\Column(type="integer", name="idsociete")
* #ORM\GeneratedValue
*/
protected $id;
public function getId() { return $this->id; }
/**
* #ORM\ManyToMany(targetEntity="ImUser", mappedBy="societes")
*/
private $users;
public function __construct()
{
$this->users = new ArrayCollection();
}
}
Get the above working then we can move on to the forms problem.

Categories