如何在多对多关系中使用接口(interface)?
在我的应用中有 3 个实体:用户、汽车和司机。用户可以将汽车和司机添加为收藏夹。所以我做了这个结构(简化):
拥有最喜欢功能的用户:
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 { /* ... */ }
但是当我使用命令
./bin/console doctrine:schema:update --force
更新我的架构时,我会得到错误[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 |
+ –– + –––––––– + + –– + –––––––– + + –––––––– + ––––––––– + ––––––––––– +
最佳答案
与 Doctrine 的ResolveTargetEntityListener
您可以按照您的方式注释与目标接口(interface)的关系,然后将其解析为特定实体。
Doctrine 文档中的更多内容:http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/cookbook/resolve-target-entity-listener.html
或者在这里,如果你使用 Symfony 框架:http://symfony.com/doc/current/doctrine/resolve_target_entity.html
但是,您无法通过此实现您想要的 - 一个接口(interface)被解析为使用“鉴别器”实现该接口(interface)的多个实体。这是不可能的AFAIK。您只能将一个接口(interface)解析为一个实体,以便在一张表中使用。
关于php - Doctrine ORM : use interface as relation for different entities?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42649553/