So, 1:M / M:1 relations don't work the way M:M relations work (obviously), but I thought that with proper configuration, you can get the same output as a M:M relation.
Basically, I needed to add another field (position), to path_offer
.
I thought I got it to work until I tried to use $path->getOffers()
which returned a PersistentCollection
instead of what I thought is forced (an ArrayCollection
of Offers). Anyway, inside the current table, I have two entries: two offers to one path. $path->getOffers()
is returning a PersistantCollection
of a PathOffer
which only has one Offer
attatched and not both.
My question is how to really use these types of relations? Because I need it with many other aspects of this project I'm working on (many M:M collections also need to be positioned)
My code is below!
Path.php
[..]
/**
* @ORM\Entity
* @ORM\Table(name="path")
*/
class Path
{
/**
* @var integer
*
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $id;
/**
* @ORM\OneToMany(targetEntity="PathOffer", mappedBy="offer", cascade={"all"})
*/
protected $offers;
[..]
PathOffer.php
[..]
/**
* @ORM\Entity
* @ORM\Table(name="path_offer")
*/
class PathOffer
{
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $id;
/**
* @ORM\ManyToOne(targetEntity="Path", inversedBy="offers", cascade={"all"})
*/
protected $path;
/**
* @ORM\ManyToOne(targetEntity="Offer", inversedBy="offers", cascade={"all"})
*/
protected $offer;
/**
* @ORM\Column(type="integer")
*/
protected $pos;
[..]
Offer.php
[..]
/**
* @ORM\Entity
* @ORM\Table(name="offer")
*/
class Offer
{
/**
* @var integer
*
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $id;
/**
* @var \ZGoffers\MainBundle\Entity\PathOffer
*
* @ORM\OneToMany(targetEntity="PathOffer", mappedBy="path", cascade={"all"})
*/
protected $paths;
[..]
I figured it out. Hopefully this post can help others who got as frustrated as I did!
Path.php
PathOffer.php
Offer.php
And for my frontend logic:
PathController.php
PathType.php (the path form)
PathOfferType.php (PathType's offers collection type)
PathHandler.php (how I process the form)
Looks like you're doing it right. Don't worry about the
PersistentCollection
/ArrayCollection
stuff -- all that matters is that they're collections.$Path->getOffers()
should indeed return a collection ofPathOffers
, and eachPathOffer
should have an offer.So it ought to work like this:
Am I missing something?