Answer the question
In order to leave comments, you need to log in
Relationships in Doctrine through an interface - how?
Hello!
I have three models: User, Car and Driver. A user can add cars and drivers to their personal favorites, so the structure is (simplified):
A user who has a favorite:
namespace Acme\AppBundle\Entities;
use Acme\AppBundle\Interfaces\HasFavorites;
/** @ORM\Entity */
class User implements HasFavorites
{
/** @ORM\ManyToMany(targetEntity="Acme\AppBundle\Entities\Favorite") */
protected $favorites;
public function getFavorites() : ArrayCollection
{
return $this->favorites;
}
public function addFavorite(Favorite $favorite)
{
$this->favorites->add($favorite);
}
}
namespace Acme\AppBundle\Entities;
use Acme\AppBundle\Interfaces\Favoritable;
/** @ORM\Entity */
class Favorite
{
/** @ORM\ManyToOne(targetEntity="Acme\AppBundle\Entities\User") */
private $owner;
/** @ORM\ManyToOne(targetEntity="Acme\AppBundle\Interfaces\Favoritable") */
private $target;
public function __construct(User $owner, Favoritable $target)
{
$this->owner = $owner;
$this->target = $target;
}
public function getOwner() : User
{
return $this->owner;
}
public function getTarget() : Favoritable
{
return $this->target;
}
}
namespace Acme\AppBundle\Entities;
use Acme\AppBundle\Interfaces\Favoritable;
/** @ORM\Entity */
class Car implements Favoritable { /* ... */ }
/** @ORM\Entity */
class Driver implements Favoritable { /* ... */ }
[Doctrine\Common\Persistence\Mapping\MappingException]
Class 'Acme\AppBundle\Interfaces\Favoritable' does not exist
$user = $this->getMockUser();
$car = $this->getMockCar();
$fav = new Favorite($user, $car);
$user->addFavorite($fav);
static::assertCount(1, $user->getFavorites());
static::assertEquals($user, $fav->getUser());
+ ––––––––––––– + + ––––––––––––– + + –––––––––––––––––––––––––––––––––– +
| users | | cars | | favorites |
+ –– + –––––––– + + –– + –––––––– + + –––––––– + ––––––––– + ––––––––––– +
| id | name | | id | name | | owner_id | target_id | target_type |
+ –– + –––––––– + + –– + –––––––– + + –––––––– + ––––––––– + ––––––––––– +
| 42 | John Doe | | 17 | BMW | | 42 | 17 | car |
+ –– + –––––––– + + –– + –––––––– + + –––––––– + ––––––––– + ––––––––––– +
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question