I'm building an app that deals with givers and companies, that own givers. Both inherit a super-class called "Organization".
I want to add an unidirectional ManyToMany relationship between them, but when I ask doctrine to implement the database, and hydrate it with fixtures, I can't retrieve the givers owned by a company.
Doctrine hasn't even created a giver_company table whatsoever which could contain the relationship information as it is supposed to do.
Here is my code:
Organization
<?php
// src/Entity/Chain/Organization.php
namespace App\Entity\Chain;
use App\Entity\User;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #ORM\Entity
* #ORM\InheritanceType("SINGLE_TABLE")
* #ORM\DiscriminatorColumn(name="type", type="string")
* #ORM\DiscriminatorMap({"association" = "Association", "super_association" = "SuperAssociation", "company" = "Company", "giver" = "Giver"})
*/
abstract class Organization
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
* #Assert\NotBlank()
*/
private $name;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
private $address;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
private $city;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
private $zipcode;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
private $SIREN;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
private $phone;
/**
* #ORM\OneToOne(targetEntity="App\Entity\Photo")
*/
private $photo;
/**
* #ORM\OneToMany(targetEntity="App\Entity\User", mappedBy="memberOf")
*/
private $members ;
/**
* Organization constructor.
*/
public function __construct()
{
$this->members = new ArrayCollection();
}
public function getId()
{
return $this->id;
}
public function getName()
{
return $this->name;
}
/**
* #param mixed $name
*/
public function setName($name): void
{
$this->name = $name;
}
public function getAddress()
{
return $this->address;
}
/**
* #param mixed $address
*/
public function setAddress($address): void
{
$this->address = $address;
}
public function getCity()
{
return $this->city;
}
/**
* #param mixed $city
*/
public function setCity($city): void
{
$this->city = $city;
}
public function getZipcode()
{
return $this->zipcode;
}
/**
* #param mixed $zipcode
*/
public function setZipcode($zipcode): void
{
$this->zipcode = $zipcode;
}
public function getSIREN()
{
return $this->SIREN;
}
/**
* #param mixed $SIREN
*/
public function setSIREN($SIREN): void
{
$this->SIREN = $SIREN;
}
public function getPhone()
{
return $this->phone;
}
/**
* #param mixed $phone
*/
public function setPhone($phone): void
{
$this->phone = $phone;
}
public function getPhoto()
{
return $this->photo;
}
/**
* #param mixed $photo
*/
public function setPhoto($photo): void
{
$this->photo = $photo;
}
public function getMembers()
{
return $this->members;
}
public function addMember(User $member)
{
if (!$this->members->contains($member)) {
$this->members->add($member);
}
}
public function removeMember(User $member){
$this->members->remove($member);
}
}
Giver
<?php
// src/Entity/Chain/Giver.php
namespace App\Entity\Chain;
use App\Entity\Photo;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity()
*/
class Giver extends Organization
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $status ;
/**
* Giver constructor.
*/
public function __construct()
{
parent::__construct();
}
/**
* #return mixed
*/
public function getId()
{
return $this->id;
}
/**
* #return mixed
*/
public function getStatus()
{
return $this->status;
}
/**
* #param mixed $status
*/
public function setStatus($status): void
{
$this->status = $status;
}
}
Company
<?php
// src/Entity/Chain/Company.php
namespace App\Entity\Chain;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity()
*/
class Company extends Organization
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255, name="company_type")
*/
private $type ;
/*
* #ORM\ManyToMany(targetEntity="App\Entity\Chain\Giver")
*/
private $givers ;
/**
* Company constructor.
*/
public function __construct()
{
parent::__construct();
$this->givers = new ArrayCollection();
}
/**
* #return mixed
*/
public function getId()
{
return $this->id;
}
/**
* #return mixed
*/
public function getType()
{
return $this->type;
}
/**
* #param mixed $type
*/
public function setType($type): void
{
$this->type = $type;
}
public function getGivers()
{
return $this->givers;
}
public function addGiver(Giver $opening)
{
if (!$this->givers->contains($opening)) {
$this->givers->add($opening);
}
}
public function removeGiver(Giver $opening){
$this->givers->remove($opening);
}
}
Your DocBlock for givers in Company is missing an "*" at the beginning. PHPDoc
Change:
/*
* #ORM\ManyToMany(targetEntity="App\Entity\Chain\Giver")
*/
private $givers ;
to
/**
* #ORM\ManyToMany(targetEntity="App\Entity\Chain\Giver")
*/
private $givers ;
Related
I have a problem with doctrine. I have two entities.
FriendRequest
class FriendRequest
{
/** #ORM\Id #ORM\Column(type="integer") #ORM\GeneratedValue **/
protected $id;
/**
* First person from friendship
*
* #ORM\OneToOne(targetEntity="User")
* #ORM\JoinColumn(name="id", referencedColumnName="id")
*/
protected $from;
/**
* Second person from friendship
*
* #ORM\OneToOne(targetEntity="User")
* #ORM\JoinColumn(name="id", referencedColumnName="id")
*/
protected $to;
/**
* #return mixed
*/
public function getId()
{
return $this->id;
}
/**
* #return mixed
*/
public function getFrom()
{
return $this->from;
}
/**
* #param mixed $from
*/
public function setFrom($from)
{
$this->from = $from;
}
/**
* #return mixed
*/
public function getTo()
{
return $this->to;
}
/**
* #param mixed $to
*/
public function setTo($to)
{
$this->to = $to;
}
}
And User
/**
* #ORM\Entity #ORM\Table(name="users")
*/
class User
{
/** #ORM\Id #ORM\Column(type="integer") #ORM\GeneratedValue **/
protected $id;
/** #ORM\Column(type="string") **/
protected $email;
/** #ORM\Column(type="string") **/
protected $password;
/** #ORM\Column(type="string") **/
protected $name;
/** #ORM\Column(type="string") **/
protected $surname;
/** #ORM\Column(type="date") **/
protected $date;
/** #ORM\Column(type="string") **/
protected $sex;
/**
* #return mixed
*/
public function getSex()
{
return $this->sex;
}
/**
* #param mixed $sex
*/
public function setSex($sex)
{
$this->sex = $sex;
}
/**
* #return mixed
*/
public function getId()
{
return $this->id;
}
/**
* #param mixed $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* #return mixed
*/
public function getEmail()
{
return $this->email;
}
/**
* #param mixed $email
*/
public function setEmail($email)
{
$this->email = $email;
}
/**
* #return mixed
*/
public function getPassword()
{
return $this->password;
}
/**
* #param mixed $password
*/
public function setPassword($password)
{
$this->password = $password;
}
/**
* #return mixed
*/
public function getName()
{
return $this->name;
}
/**
* #param mixed $name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* #return mixed
*/
public function getSurname()
{
return $this->surname;
}
/**
* #param mixed $surname
*/
public function setSurname($surname)
{
$this->surname = $surname;
}
/**
* #return mixed
*/
public function getDate()
{
return $this->date;
}
/**
* #param mixed $date
*/
public function setDate($date)
{
$this->date = $date;
}
}
I tried to create the new friendship request.
$from = $this->entity_manager->getRepository(User::class)->findOneBy(
["id" => $my_id]
);
$to = $this->entity_manager->getRepository(User::class)->findOneBy(
["id" => $target_user_id]
);
/** #var FriendRequest $friend_request */
$friend_request = new FriendRequest();
$friend_request->setFrom($from);
$friend_request->setTo($to);
$this->entity_manager->persist($friend_request);
$this->entity_manager->flush();
But it does not work. Doctrine shows me error:
An exception occurred while executing 'INSERT INTO friendRequest (id) VALUES (?)' with params [186]:
SQLSTATE[HY000]: General error: 1364 Field 'from' doesn't have a default value.
I tried to print $from ad $to, but they are correct. Is there someone who know what does it mean? I spent a lot of time with it, but I dont know...
I think your issue comes from the declaration of the $from and $to attributes in the FriendRequest entity class, if you try to update your database model you are going to get an error like this:
[Doctrine\ORM\Mapping\MappingException]
Duplicate definition of column 'id' on entity 'FriendRequest' in a field or discriminator column mapping.
Since you have assigned the same name 'id' for two different attributes. Probably you have in your database two columns From and To, but they are not mapping with your model, that's why you get an error saying from doesn't have a default value. Since the column name in the database are not sync with the name of the attributes in your entity.
Assuming you already have a FriendRequest table and you are using 'from' and 'to' as the column names this should be the update of the FriendRequest entity class.
class FriendRequest
{
/** #ORM\Id #ORM\Column(type="integer") #ORM\GeneratedValue **/
protected $id;
/**
* First person from friendship
*
* #ORM\OneToOne(targetEntity="User")
* #ORM\JoinColumn(name="from", referencedColumnName="id")
*/
protected $from;
/**
* Second person from friendship
*
* #ORM\OneToOne(targetEntity="User")
* #ORM\JoinColumn(name="to", referencedColumnName="id")
*/
protected $to;
...
}
I am struggling with the following. I am writing a basic User / Order relationship where a number of users play different roles. Each order is therefore linked to a user who is the initiator of the order, the courier (the user who is gonna pick up the order), the recipient, the user who is going to receive the order.
It stands that the Order table will have a number of relationships with the User table. Each Order will have a single user for each group, while each user can potentially have multiple relationships to the various Orders.
Unfortunately, I keep getting this error and I am not sure how to get around it:
An exception occurred while executing 'SELECT t0.id AS id1, t0.size AS
size2, t0.total AS total3, t0.initial_offer AS initial_offer4,
t0.user_order_owner AS user_order_owner5, t0.user_order_to AS
user_order_to6, t0.user_order_from AS user_order_from7,
t0.user_order_courier AS user_order_courier8, t0.event_collection_id
AS event_collection_id9, t0.event_delivery_id AS event_delivery_id10,
t0.currency_id AS currency_id11, t0.capacity_limitation_id AS
capacity_limitation_id12, t0.negotiation_id AS negotiation_id13,
t0.address_from_id AS address_from_id14, t0.address_to_id AS
address_to_id15 FROM order t0 WHERE t0.user_order_courier = ?' with
params [1]:
OR:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an
error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near 'order t0 WHERE
t0.user_order_courier = '1'' at line 1
Each Order in the system will have a user who is a:
Courier
Recipient
Sender
I am bug testing with the orderCourier join and joins are as follows:
Order Entity::
/**
* #ORM\ManyToOne(targetEntity="RoleBasedUser\Entity\User", inversedBy="orderCourier")
* #ORM\JoinColumn(name="user_order_courier", referencedColumnName="id")
*/
private $userCourier;
User Entity
/**
* #ORM\OneToMany(targetEntity="Negotiation\Entity\Order", mappedBy="userCourier")
*/
private $orderCourier;
The full entities are as follows:
My User Entity:
<?php
namespace RoleBasedUser\Entity;
use Doctrine\ORM\Mapping AS ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Gedmo\Mapping\Annotation as Gedmo;
use Rbac\Role\RoleInterface;
use ZfcRbac\Identity\IdentityInterface;
/**
* Class User
* #package RoleBasedUser\Entity
*
* #ORM\Entity(repositoryClass="UserRepository")
* #ORM\Table(name="rbu_users")
*/
class User implements IdentityInterface
{
/**
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(name="id", type="integer", nullable=false)
*
* #var int
* #access protected
*/
private $id;
/**
* #ORM\Column(type="string", length=32, nullable=false, name="uuid")
*
* #var string
* #access private
*/
private $uuid;
/**
* #ORM\Column(type="string", unique=true, length=255, nullable=true, name="email")
*
* #var string
* #access private
*/
private $email;
/**
* #ORM\Column(type="smallint", nullable=true, name="state")
*
* #var integer
* #access private
*/
private $state;
/**
* #ORM\OneToMany(targetEntity="RoleBasedUser\Entity\LocationHistory", mappedBy="user")
*/
private $location;
/**
* #ORM\Column(nullable=true)
*/
private $parent;
/**
* #ORM\Column(nullable=true)
*/
private $firstName;
/**
* #ORM\Column(nullable=true)
*/
private $lastName;
/**
* #ORM\Column(nullable=true)
*/
private $password;
// /**
// * #ORM\OneToMany(targetEntity="Negotiation\Entity\Order", mappedBy="userOwner")
// */
// private $orderOwner;
//
// /** `
// * #ORM\OneToMany(targetEntity="Negotiation\Entity\Order", mappedBy="userTo")
// */
// private $orderTo;
//
// /**
// * #ORM\OneToMany(targetEntity="Negotiation\Entity\Order", mappedBy="userFrom")
// */
// private $orderFrom;
//
/**
* #ORM\OneToMany(targetEntity="Negotiation\Entity\Order", mappedBy="userCourier")
*/
private $orderCourier;
/**
* #ORM\OneToMany(targetEntity="RoleBasedUser\Entity\Feedback", mappedBy="client")
*/
private $clientFeedback;
/**
* #ORM\OneToMany(targetEntity="RoleBasedUser\Entity\Feedback", mappedBy="courier")
*/
private $feedbackCourier;
/**
* #ORM\OneToMany(targetEntity="RoleBasedUser\Entity\UserAvailability", mappedBy="user")
*/
private $pleaseUseMe;
/**
* #ORM\OneToMany(targetEntity="RoleBasedUser\Entity\UserStoredLocations", mappedBy="user")
*/
private $userAddresses;
/**
* #ORM\ManyToOne(targetEntity="RoleBasedUser\Entity\Corporate", inversedBy="user")
* #ORM\JoinColumn(name="corporate_id", referencedColumnName="id")
*/
private $corporate;
/**
* #ORM\OneToMany(targetEntity="Negotiation\Entity\Offer", mappedBy="user")
*/
private $offer;
/**
* #ORM\ManyToMany(targetEntity="HierarchicalRole")
* #ORM\JoinTable(name="rbu_users_roles",
* joinColumns={#ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="role_id", referencedColumnName="id")}
* )
*
* #var Collection
* #access private
*/
private $roles;
/**
* #Gedmo\Timestampable(on="create")
* #ORM\Column(type="datetime")
*
* #var \DateTime
* #access protected
*/
protected $created;
/**
* #Gedmo\Timestampable(on="update")
* #ORM\Column(type="datetime")
*
* #var \DateTime
* #access protected
*/
protected $modified;
/**
* Initiates all ArrayCollections
*
* #access public
*/
public function __construct()
{
$this->roles = new ArrayCollection();
$this->orderOwner = new ArrayCollection();
$this->orderTo = new ArrayCollection();
$this->orderFrom = new ArrayCollection();
$this->orderCourier = new ArrayCollection();
$this->clientFeedback = new ArrayCollection();
$this->feedbackCourier = new ArrayCollection();
$this->pleaseUseMe = new ArrayCollection();
$this->userAddresses = new ArrayCollection();
$this->offer = new ArrayCollection();
}
/**
* {#inheritDoc}
*/
public function getRoles()
{
return $this->roles->toArray();
}
public function getRole()
{
if(!empty($this->getRoles()[0])) {
$roleObject = $this->getRoles()[0];
return $roleObject->getName();
} else return "Not set";
}
/**
* Set the list of roles
* #param Collection $roles
*/
public function setRoles(Collection $roles)
{
$this->roles->clear();
foreach ($roles as $role) {
$this->roles[] = $role;
}
}
/**
* Add one role to roles list
* #param \Rbac\Role\RoleInterface $role
*/
public function addRole(RoleInterface $role)
{
$this->roles[] = $role;
}
/**
* Add Roles to the collection
* #param Collection $roles
*/
public function addRoles(Collection $roles)
{
foreach($roles as $role) {
$this->roles->add($role);
}
}
/**
* Remove Roles from the collection
* #param Collection $roles
*/
public function removeRoles(Collection $roles)
{
foreach($roles as $role) {
$this->roles->removeElement($role);
}
}
/**
* #return mixed
*/
public function getCorporate()
{
return $this->corporate;
}
/**
* #param mixed $corporate
*/
public function setCorporate($corporate)
{
$this->corporate = $corporate;
}
/**
* #return \DateTime
*/
public function getCreated()
{
return $this->created;
}
/**
* #param \DateTime $created
*/
public function setCreated($created)
{
$this->created = $created;
}
/**
* #return mixed
*/
public function getFirstName()
{
return $this->firstName;
}
/**
* #param mixed $firstName
*/
public function setFirstName($firstName)
{
$this->firstName = $firstName;
}
/**
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* #param int $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* #return mixed
*/
public function getLastName()
{
return $this->lastName;
}
/**
* #param mixed $lastName
*/
public function setLastName($lastName)
{
$this->lastName = $lastName;
}
/**
* #return mixed
*/
public function getLocation()
{
return $this->location;
}
/**
* #param mixed $location
*/
public function setLocation($location)
{
$this->location = $location;
}
/**
* #return \DateTime
*/
public function getModified()
{
return $this->modified;
}
/**
* #param \DateTime $modified
*/
public function setModified($modified)
{
$this->modified = $modified;
}
/**
* #return mixed
*/
public function getParent()
{
return $this->parent;
}
/**
* #param mixed $parent
*/
public function setParent($parent)
{
$this->parent = $parent;
}
/**
* #return mixed
*/
public function getPassword()
{
return $this->password;
}
/**
* #param mixed $password
*/
public function setPassword($password)
{
$this->password = $password;
}
/**
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* #param string $email
*/
public function setEmail($email)
{
$this->email = $email;
}
/**
* #return string
*/
public function getUuid()
{
return $this->uuid;
}
/**
* #param string $uuid
*/
public function setUuid($uuid)
{
$this->uuid = $uuid;
}
/**
* {#inheritDoc}
*/
public function getOrderOwner()
{
return $this->orderOwner->toArray();
}
/**
* #param Collection $orderOwner
*/
public function setOrderOwner(Collection $orderOwner)
{
$this->orderOwner->clear();
foreach ($orderOwner as $order) {
$this->orderOwner[] = $order;
}
}
/**
* #param Collection $orderOwner
*/
public function addOrderOwner(Collection $orderOwner)
{
foreach($orderOwner as $order) {
$this->orderOwner->add($order);
}
}
/**
* #param Collection $orderOwner
*/
public function removeOrderOwner(Collection $orderOwner)
{
foreach($orderOwner as $order) {
$this->orderOwner->removeElement($order);
}
}
/**
* {#inheritDoc}
*/
public function getOrderTo()
{
return $this->orderTo->toArray();
}
/**
* #param Collection $orderTo
*/
public function setOrderTo(Collection $orderTo)
{
$this->orderTo->clear();
foreach ($orderTo as $order) {
$this->orderTo[] = $order;
}
}
/**
* #param Collection $orderTo
*/
public function addOrderTo(Collection $orderTo)
{
foreach($orderTo as $order) {
$this->orderTo->add($order);
}
}
/**
* #param Collection $orderTo
*/
public function removeOrderTo(Collection $orderTo)
{
foreach($orderTo as $order) {
$this->orderTo->removeElement($order);
}
}
/**
* {#inheritDoc}
*/
public function getOrderFrom()
{
return $this->orderFrom->toArray();
}
/**
* #param Collection $orderFrom
*/
public function setOrderFrom(Collection $orderFrom)
{
$this->orderFrom->clear();
foreach ($orderFrom as $order) {
$this->orderFrom[] = $order;
}
}
/**
* #param Collection $orderFrom
*/
public function addOrderFrom(Collection $orderFrom)
{
foreach($orderFrom as $order) {
$this->orderFrom->add($order);
}
}
/**
* #param Collection $orderFrom
*/
public function removeOrderFrom(Collection $orderFrom)
{
foreach($orderFrom as $order) {
$this->orderFrom->removeElement($order);
}
}
/**
* {#inheritDoc}
*/
public function getOrderCourier()
{
return $this->orderCourier->toArray();
}
/**
* #param Collection $orderCourier
*/
public function setOrderCourier(Collection $orderCourier)
{
$this->orderCourier->clear();
foreach ($orderCourier as $order) {
$this->orderCourier[] = $order;
}
}
/**
* #param Collection $orderCourier
*/
public function addOrderCourier(Collection $orderCourier)
{
foreach($orderCourier as $order) {
$this->orderCourier->add($order);
}
}
/**
* #param Collection $orderCourier
*/
public function removeOrderCourier(Collection $orderCourier)
{
foreach($orderCourier as $order) {
$this->orderCourier->removeElement($order);
}
}
/**
* {#inheritDoc}
*/
public function getClientFeedback()
{
return $this->clientFeedback->toArray();
}
/**
* #param Collection $clientFeedback
*/
public function setClientFeedback(Collection $clientFeedback)
{
$this->clientFeedback->clear();
foreach ($clientFeedback as $feedback) {
$this->clientFeedback[] = $feedback;
}
}
/**
* #param Collection $clientFeedback
*/
public function addClientFeedback(Collection $clientFeedback)
{
foreach($clientFeedback as $feedback) {
$this->clientFeedback->add($feedback);
}
}
/**
* #param Collection $clientFeedback
*/
public function removeClientFeedback(Collection $clientFeedback)
{
foreach($clientFeedback as $feedback) {
$this->clientFeedback->removeElement($feedback);
}
}
/**
* {#inheritDoc}
*/
public function getFeedbackCourier()
{
return $this->feedbackCourier->toArray();
}
/**
* #param Collection $feedbackCourier
*/
public function setFeedbackCourier(Collection $feedbackCourier)
{
$this->feedbackCourier->clear();
foreach ($feedbackCourier as $feedback) {
$this->feedbackCourier[] = $feedback;
}
}
/**
* #param Collection $feedbackCourier
*/
public function addFeedbackCourier(Collection $feedbackCourier)
{
foreach($feedbackCourier as $feedback) {
$this->feedbackCourier->add($feedback);
}
}
/**
* #param Collection $feedbackCourier
*/
public function removeFeedbackCourier(Collection $feedbackCourier)
{
foreach($feedbackCourier as $feedback) {
$this->feedbackCourier->removeElement($feedback);
}
}
/**
* {#inheritDoc}
*/
public function getPleaseUseMe()
{
return $this->pleaseUseMe->toArray();
}
/**
* #param Collection $pleaseUseMe
*/
public function setPleaseUseMe(Collection $pleaseUseMe)
{
$this->pleaseUseMe->clear();
foreach ($pleaseUseMe as $useme) {
$this->pleaseUseMe[] = $useme;
}
}
/**
* #param Collection $pleaseUseMe
*/
public function addPleaseUseMe(Collection $pleaseUseMe)
{
foreach($pleaseUseMe as $useme) {
$this->pleaseUseMe->add($useme);
}
}
/**
* #param Collection $pleaseUseMe
*/
public function removePleaseUseMe(Collection $pleaseUseMe)
{
foreach($pleaseUseMe as $useme) {
$this->pleaseUseMe->removeElement($useme);
}
}
/**
* {#inheritDoc}
*/
public function getUserAddresses()
{
return $this->userAddresses->toArray();
}
/**
* #param Collection $userAddresses
*/
public function setUserAddresses(Collection $userAddresses)
{
$this->userAddresses->clear();
foreach ($userAddresses as $address) {
$this->userAddresses[] = $address;
}
}
/**
* #param Collection $userAddresses
*/
public function addUserAddresses(Collection $userAddresses)
{
foreach($userAddresses as $address) {
$this->userAddresses->add($address);
}
}
/**
* #param Collection $userAddresses
*/
public function removeUserAddresses(Collection $userAddresses)
{
foreach($userAddresses as $address) {
$this->userAddresses->removeElement($address);
}
}
/**
* {#inheritDoc}
*/
public function getOffer()
{
return $this->offer->toArray();
}
/**
* #param Collection $offer
*/
public function setOffer(Collection $offer)
{
$this->offer->clear();
foreach ($offer as $n) {
$this->offer[] = $n;
}
}
/**
* #param Collection $offer
*/
public function addOffer(Collection $offer)
{
foreach($offer as $n) {
$this->offer->add($n);
}
}
/**
* #param Collection $offer
*/
public function removeOffer(Collection $offer)
{
foreach($offer as $n) {
$this->offer->removeElement($n);
}
}
/**
* #param int $state
*/
public function setState($state)
{
$this->state = $state;
}
/**
* #return int
*/
public function getState()
{
return $this->state;
}
}
And my Order Entity:
<?php
namespace Negotiation\Entity;
use Doctrine\ORM\Mapping AS ORM;
/**
* #ORM\Entity
*/
class Order
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(type="integer", nullable=true)
*/
private $size;
/**
* #ORM\Column(type="float", length=15, nullable=true)
*/
private $total;
/**
* #ORM\Column(nullable=true)
*/
private $initialOffer;
/**
* #ORM\ManyToOne(targetEntity="RoleBasedUser\Entity\User", inversedBy="orderOwner")
* #ORM\JoinColumn(name="user_order_owner", referencedColumnName="id")
*/
private $userOwner;
/**
* #ORM\ManyToOne(targetEntity="RoleBasedUser\Entity\User", inversedBy="orderTo")
* #ORM\JoinColumn(name="user_order_to", referencedColumnName="id")
*/
private $userTo;
/**
* #ORM\OneToMany(targetEntity="RoleBasedUser\Entity\Feedback", mappedBy="order")
*/
private $feedback;
/**
* #ORM\ManyToOne(targetEntity="RoleBasedUser\Entity\User", inversedBy="orderFrom")
* #ORM\JoinColumn(name="user_order_from", referencedColumnName="id")
*/
private $userFrom;
/**
* #ORM\ManyToOne(targetEntity="RoleBasedUser\Entity\User", inversedBy="orderCourier")
* #ORM\JoinColumn(name="user_order_courier", referencedColumnName="id")
*/
private $userCourier;
/**
* #ORM\ManyToOne(targetEntity="Negotiation\Entity\Event", inversedBy="wayBillCollection")
*/
private $eventCollection;
/**
* #ORM\ManyToOne(targetEntity="Negotiation\Entity\Event", inversedBy="wayBillDelivery")
*/
private $eventDelivery;
/**
* #ORM\ManyToOne(targetEntity="Negotiation\Entity\Currency", inversedBy="order")
*/
private $currency;
/**
* #ORM\ManyToOne(targetEntity="Negotiation\Entity\CapacityLimitation", inversedBy="order")
*/
private $capacityLimitation;
/**
* #ORM\ManyToOne(targetEntity="Negotiation\Entity\Negotiation", inversedBy="order")
*/
private $negotiation;
/**
* #ORM\ManyToOne(targetEntity="Negotiation\Entity\Address", inversedBy="orderFrom")
*/
private $addressFrom;
/**
* #ORM\ManyToOne(targetEntity="Negotiation\Entity\Address", inversedBy="orderTo")
*/
private $addressTo;
/**
* #return mixed
*/
public function getAddressFrom()
{
return $this->addressFrom;
}
/**
* #param mixed $addressFrom
*/
public function setAddressFrom($addressFrom)
{
$this->addressFrom = $addressFrom;
}
/**
* #return mixed
*/
public function getAddressTo()
{
return $this->addressTo;
}
/**
* #param mixed $addressTo
*/
public function setAddressTo($addressTo)
{
$this->addressTo = $addressTo;
}
/**
* #return mixed
*/
public function getCapacityLimitation()
{
return $this->capacityLimitation;
}
/**
* #param mixed $capacityLimitation
*/
public function setCapacityLimitation($capacityLimitation)
{
$this->capacityLimitation = $capacityLimitation;
}
/**
* #return mixed
*/
public function getCurrency()
{
return $this->currency;
}
/**
* #param mixed $currency
*/
public function setCurrency($currency)
{
$this->currency = $currency;
}
/**
* #return mixed
*/
public function getEventCollection()
{
return $this->eventCollection;
}
/**
* #param mixed $eventCollection
*/
public function setEventCollection($eventCollection)
{
$this->eventCollection = $eventCollection;
}
/**
* #return mixed
*/
public function getEventDelivery()
{
return $this->eventDelivery;
}
/**
* #param mixed $eventDelivery
*/
public function setEventDelivery($eventDelivery)
{
$this->eventDelivery = $eventDelivery;
}
/**
* #return mixed
*/
public function getFeedback()
{
return $this->feedback;
}
/**
* #param mixed $feedback
*/
public function setFeedback($feedback)
{
$this->feedback = $feedback;
}
/**
* #return mixed
*/
public function getId()
{
return $this->id;
}
/**
* #param mixed $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* #return mixed
*/
public function getInitialOffer()
{
return $this->initialOffer;
}
/**
* #param mixed $initialOffer
*/
public function setInitialOffer($initialOffer)
{
$this->initialOffer = $initialOffer;
}
/**
* #return mixed
*/
public function getNegotiation()
{
return $this->negotiation;
}
/**
* #param mixed $negotiation
*/
public function setNegotiation($negotiation)
{
$this->negotiation = $negotiation;
}
/**
* #return mixed
*/
public function getSize()
{
return $this->size;
}
/**
* #param mixed $size
*/
public function setSize($size)
{
$this->size = $size;
}
/**
* #return mixed
*/
public function getTotal()
{
return $this->total;
}
/**
* #param mixed $total
*/
public function setTotal($total)
{
$this->total = $total;
}
/**
* #return mixed
*/
public function getUserCourier()
{
return $this->userCourier;
}
/**
* #param mixed $userCourier
*/
public function setUserCourier($userCourier)
{
$this->userCourier = $userCourier;
}
/**
* #return mixed
*/
public function getUserFrom()
{
return $this->userFrom;
}
/**
* #param mixed $userFrom
*/
public function setUserFrom($userFrom)
{
$this->userFrom = $userFrom;
}
/**
* #return mixed
*/
public function getUserOwner()
{
return $this->userOwner;
}
/**
* #param mixed $userOwner
*/
public function setUserOwner($userOwner)
{
$this->userOwner = $userOwner;
}
/**
* #return mixed
*/
public function getUserTo()
{
return $this->userTo;
}
/**
* #param mixed $userTo
*/
public function setUserTo($userTo)
{
$this->userTo = $userTo;
}
}
EDIT:
The errors are appearing when I attempt to edit the user and the exceptions occur on: $this->updateForm->bind($object);
$user_id = (int) $this->params()->fromRoute('user_id', 0);
$object = $this->userService->find($user_id);
$prg = $this->prg();
if ($prg instanceof Response) {
return $prg;
} elseif ($prg === false) {
$this->updateForm->bind($object);
return $this->getVM()->setVariables([
'user' => $object,
'form' => $this->updateForm
]);
}
EDIT:
Essentially these three tables cause the problem, as soon as I remove them , all works as expected:
// /**
// * #ORM\OneToMany(targetEntity="Negotiation\Entity\Order", mappedBy="userOwner")
// */
// private $orderOwner;
// /** `
// * #ORM\OneToMany(targetEntity="Negotiation\Entity\Order", mappedBy="userTo")
// */
// private $orderTo;
// /**
// * #ORM\OneToMany(targetEntity="Negotiation\Entity\Order", mappedBy="userFrom")
// */
// private $orderFrom;
// /**
// * #ORM\OneToMany(targetEntity="Negotiation\Entity\Order", mappedBy="userCourier")
// */
// private $orderCourier;
The solution to this problem was to sort out my getters and setters. I was too focused on the annotations of the problem that I never looked towards them for a possible error.
Thanks to Svengali who got me to re-look at what I was doing wrong.
My Getters/Setters where originally like this:
/**
* {#inheritDoc}
*/
public function getOrderCourier()
{
return $this->orderCourier->toArray();
}
/**
* #param Collection $orderCourier
*/
public function setOrderCourier(Collection $orderCourier)
{
$this->orderCourier->clear();
foreach ($orderCourier as $order) {
$this->orderCourier[] = $order;
}
}
/**
* #param Collection $orderCourier
*/
public function addOrderCourier(Collection $orderCourier)
{
foreach($orderCourier as $order) {
$this->orderCourier->add($order);
}
}
/**
* #param Collection $orderCourier
*/
public function removeOrderCourier(Collection $orderCourier)
{
foreach($orderCourier as $order) {
$this->orderCourier->removeElement($order);
}
}
I changed them to:
/**
* #return mixed
*/
public function getOrderCourier()
{
return $this->orderCourier;
}
/**
* #param mixed $orderCourier
*/
public function setOrderCourier($orderCourier)
{
$this->orderCourier = $orderCourier;
}
And the problem no longer persists.
Thanks for the input, although it may have only been a simple question, often this is all a developer needs in order to push them in the right direction.
I mean I have these two classes (one to many relationship). As you can appreciate in both I have included cascade={"persist"}.
namespace Project\FrontendBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="task")
*/
class Task
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(type="string", length=255, name="description", nullable=true)
*/
protected $description;
/**
* #ORM\OneToMany(targetEntity="Tag", mappedBy="task", cascade={"persist"})
**/
protected $tags;
/*************************************/
public function __toString()
{
return $this->description;
}
/**
* Constructor
*/
public function __construct()
{
$this->tags = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set description
*
* #param string $description
* #return Task
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Add tags
*
* #param \Project\FrontendBundle\Entity\Tag $tags
* #return Task
*/
public function addTag(\Project\FrontendBundle\Entity\Tag $tags)
{
$this->tags[] = $tags;
return $this;
}
/**
* Remove tags
*
* #param \Project\FrontendBundle\Entity\Tag $tags
*/
public function removeTag(\Project\FrontendBundle\Entity\Tag $tags)
{
$this->tags->removeElement($tags);
}
/**
* Get tags
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getTags()
{
return $this->tags;
}
}
namespace Project\FrontendBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="tag")
*/
class Tag
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(type="string", length=255, name="name", nullable=true)
*/
protected $name;
/**
* #ORM\ManyToOne(targetEntity="Task", inversedBy="tags", cascade={"persist"})
* #ORM\JoinColumn(name="task_id", referencedColumnName="id")
**/
private $task;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Tag
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set task
*
* #param \Project\FrontendBundle\Entity\Task $task
* #return Tag
*/
public function setTask(\Project\FrontendBundle\Entity\Task $task = null)
{
$this->task = $task;
return $this;
}
/**
* Get task
*
* #return \Project\FrontendBundle\Entity\Task
*/
public function getTask()
{
return $this->task;
}
}
In my controller I have this:
$task = new Task();
$tag = new Tag();
$task->addTag($tag);
$em = $this->getDoctrine()->getManager();
$em->persist($item);
$em->flush();
but the foreign key is always NULL, why?
I think in the Task class, the addTag and removeTag should look like this:
public function addTag($tag)
{
$tag->setTask($this);
$this->tags->add($tag);
}
public function removeTag($tag)
{
$tag->setTask(null);
$this->tags->removeElement($tag);
}
Or if you want to add and remove many tags in one function call use these:
public function addTags(Collection $tags)
{
foreach ($tags as $tag) {
$tag->setTask($this);
$this->tags->add($tag);
}
}
public function removeTags(Collection $tags)
{
foreach ($tags as $tag) {
$tag->setTask(null);
$this->tags->removeElement($tag);
}
}
I have the following:
User have one group, group can have many users
User
<?php namespace Application\Model;
use Doctrine\Common\Collections;
use Doctrine\ORM\Mapping as ORM;
/**
* User model
* Read-only entity
* #ORM\Table(name="VLOGGER_WEBCALENDAR_USR")
* #ORM\Entity
* #package Application\Model
*/
class User
{
/**
* #var int
* #ORM\Id
* #ORM\Column(name="USR_ID", type="integer")
*/
protected $id;
/**
* #var string
* #ORM\Column(name="USR_LOGIN", type="string")
*/
protected $login;
/**
* #var string
* #ORM\Column(name="USR_CODE", type="string")
*/
protected $code;
/**
* #var int
* #ORM\Column(name="GRP_ID", type="integer")
*/
protected $groupId;
/**
* #var string
* #ORM\Column(name="GRP_CODE", type="string")
*/
protected $groupCode;
/**
* #var User\Group
* #ORM\ManyToOne(targetEntity="Application\Model\User\Group",fetch="EAGER")
* #ORM\JoinColumn(name="GRP_ID", referencedColumnName="GRP_ID")
*/
protected $group;
/**
* #var Event
* #ORM\OneToMany(targetEntity="Application\Model\Event", mappedBy="user")
* #ORM\JoinColumn(name="USR_ID", referencedColumnName="USR_ID")
*/
protected $events;
/**
* Constructor
*/
public function __construct()
{
$this->events = new Collections\ArrayCollection();
}
/**
* #return string
*/
public function getCode()
{
return $this->code;
}
/**
* #param string $code
* #return User
*/
public function setCode($code)
{
$this->code = $code;
return $this;
}
/**
* #return Event
*/
public function getEvents()
{
return $this->events;
}
/**
* #param Event $events
* #return User
*/
public function setEvents($events)
{
$this->events = $events;
return $this;
}
/**
* #return User\Group
*/
public function getGroup()
{
return $this->group;
}
/**
* #param User\Group $group
* #return User
*/
public function setGroup($group)
{
$this->group = $group;
return $this;
}
/**
* #return string
*/
public function getGroupCode()
{
return $this->groupCode;
}
/**
* #param string $groupCode
* #return User
*/
public function setGroupCode($groupCode)
{
$this->groupCode = $groupCode;
return $this;
}
/**
* #return int
*/
public function getGroupId()
{
return $this->groupId;
}
/**
* #param int $groupId
* #return User
*/
public function setGroupId($groupId)
{
$this->groupId = $groupId;
return $this;
}
/**
* #return mixed
*/
public function getId()
{
return $this->id;
}
/**
* #param mixed $id
* #return User
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* #return string
*/
public function getLogin()
{
return $this->login;
}
/**
* #param string $login
* #return User
*/
public function setLogin($login)
{
$this->login = $login;
return $this;
}
}
Group
<?php namespace Application\Model\User;
use Application\Model;
use Doctrine\Common\Collections;
use Doctrine\ORM\Mapping as ORM;
/**
* User group model
* Read-only entity
* #ORM\Table(name="VLOGGER_WEBCALENDAR_GRP")
* #ORM\Entity
* #package Application\Model
*/
class Group
{
/**
* #var int
* #ORM\Id
* #ORM\Column(name="GRP_ID", type="integer")
*/
protected $id;
/**
* #var string
* #ORM\Column(name="GRP_CODE", type="string")
*/
protected $code;
/**
* #var Collections\ArrayCollection
* #ORM\OneToMany(targetEntity="Application\Model\User", mappedBy="group")
* #ORM\JoinColumn(name="GRP_ID", referencedColumnName="GRP_ID")
*/
protected $users;
/**
* Constructor
*/
public function __construct()
{
$this->users = new Collections\ArrayCollection();
}
/**
* #return mixed
*/
public function getCode()
{
return $this->code;
}
/**
* #param mixed $code
* #return Group
*/
public function setCode($code)
{
$this->code = $code;
return $this;
}
/**
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* #param int $id
* #return Group
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* #return mixed
*/
public function getUsers()
{
return $this->users;
}
/**
* #param mixed $users
* #return Group
*/
public function setUsers($users)
{
$this->users = $users;
return $this;
}
}
When I try to retrieve the relation from the groups, it works great, but when I slect the users and try to get their group, Doctrine create some proxy objects and the result is an empty object with only the relationship key filled.
Can someone point me to the good direction ?
Here my code:
$query = $em->createQueryBuilder()
->select('u')
->from('Application\Model\User', 'u');
$data = $query->getQuery()->getResult();
$data = reset($data);
var_dump($data->getGroup()); // proxy
###########################
$query = $em->createQueryBuilder()
->select('g')
->from('Application\Model\User\Group', 'g');
$data = $query->getQuery()->getResult();
$data = reset($data);
var_dump($data->getUsers()); // ok
you don't need the $GRP_ID in the User Entity - it's already mapped with the $group relation. Doctrine handles the IDs automatically.
Also your naming-convention looks a bit weird. Normally you should use lowe-camel-case (to save you from strange errors)
Example:
$USR_CODE should be $usrCode -> to match your getter/setter: setUsrCode(), getUsrCode().
just noticed: you don't have any setters. You have to define setters for your attributes, with the naming-convention (look at my example above)
Edit:
you can map the column with the doctrine orm notation:
/**
*
* #ORM\Column(name="USR_CODE", type="string")
*/
private $usrCode;
And yes, you need setters otherwise doctrine won't be able to set the values.
You also need addUser() and removeUser() functions (since user is a Collection):
public function addUsers(Collection $users)
{
foreach($users as $user)
{
if( ! $this->users->contains($user))
{
$this->users->add($user);
$user->setGroup($this);
}
}
}
public function removeUsers(Collection $users)
{
foreach($users as $user)
{
if($this->users->contains($user)){
$this->users->remove($user);
$user->setGroup(null);
}
}
}
I'm trying remove a registry from my database using doctrine 2, but I'm getting the follow error:
Catchable fatal error: Argument 1 passed to Doctrine\ORM\Mapping\DefaultQuoteStrategy::getJoinTableName() must be an array, null given, called in /home/triangulum/www/pedal/vendor/doctrine/orm/lib/Doctrine/ORM/Persisters/BasicEntityPersister.php on line 1020 and defined in /home/triangulum/www/pedal/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/DefaultQuoteStrategy.php on line 86
I have 3 tables:
grupo = id, name
permissao = id, name
grupo_permissao = grupo_id, permissao_id
My entitys:
Grupo:
<?php
namespace User\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Entity
* #ORM\Table(name="grupo")
* #ORM\Entity(repositoryClass="User\Entity\GrupoRepository")
*/
class Grupo {
public function __construct($options=null) {
Configurator::configure($this, $options);
$this->permissoes = new ArrayCollection();
}
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue
* #var int
*/
protected $id;
/**
* #ORM\Column(type="text")
* #var string
*/
protected $nome;
/**
* #ORM\ManyToMany(targetEntity="User\Entity\Permissao", mappedBy="grupo", cascade={"remove"})
*/
protected $permissoes;
public function getPermissoes()
{
return $this->permissoes;
}
public function getId() {
return $this->id;
}
public function setId($id) {
$this->id = $id;
}
public function getNome() {
return $this->nome;
}
public function setNome($nome) {
$this->nome = $nome;
}
public function toArray()
{
return array
(
'id' => $this->getId(),
'nome' => $this->getNome()
);
}
}
?>
Permissao:
<?php
namespace User\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Entity
* #ORM\Table(name="permissao")
* #ORM\Entity(repositoryClass="User\Entity\PermissaoRepository")
*/
class Permissao {
public function __construct($options=null) {
Configurator::configure($this, $options);
$this->grupos = new ArrayCollection();
}
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue
* #var int
*/
protected $id;
/**
* #ORM\Column(type="text")
* #var string
*/
protected $nome;
/**
* #ORM\ManyToMany(targetEntity="User\Entity\Grupo", inversedBy="permissao", cascade={"persist", "remove"})
* #ORM\JoinTable(name="grupo_permissao",
* joinColumns={#ORM\JoinColumn(name="permissao_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="grupo_id", referencedColumnName="id")}
* )
*/
protected $grupos;
public function getGrupos() {
return $this->grupos;
}
public function getId() {
return $this->id;
}
public function setId($id) {
$this->id = $id;
}
public function getNome() {
return $this->nome;
}
public function setNome($nome) {
$this->nome = $nome;
}
public function toArray()
{
return array
(
'id' => $this->getId(),
'nome' => $this->getNome()
);
}
}
?>
remove:
public function delete($id)
{
$entity = $this->entityManager->find('User\Entity\Grupo', $id);
if($entity)
{
$this->entityManager->remove($entity);
$this->entityManager->flush();
return $id;
}
}
What am I doing wrong?
I think you have a problem with your mappedBy and inversedBy attributes in the manyToMany annotations. They should match the other entities property name, grupos and permissoes. Try this:
/**
* #ORM\ManyToMany(targetEntity="User\Entity\Permissao", mappedBy="grupos", cascade={"remove"})
*/
protected $permissoes;
/**
* #ORM\ManyToMany(targetEntity="User\Entity\Grupo", inversedBy="permissoes", cascade={"persist", "remove"})
* #ORM\JoinTable(name="grupo_permissao",
* joinColumns={#ORM\JoinColumn(name="permissao_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="grupo_id", referencedColumnName="id")}
* )
*/
protected $grupos;