我有2个实体 - 用户和标签。不能得到教条2多对多的关系去工作
这是我的用户:
<?php
namespace Project\Model;
/**
* @Entity
* @Table(name="users")
* @InheritanceType("JOINED")
* @DiscriminatorColumn(name="discr", type="string")
* @DiscriminatorMap({"user" = "User", "client" = "Client", "staff" = "Staff"})
**/
class User implements \JsonSerializable {
/** @Id @Column(type="integer") @GeneratedValue **/
protected $id;
/** @Column(type="string", name="first_name") **/
protected $firstName;
/**
* @ManyToMany(targetEntity="Project\Model\Tag", inversedBy="users")
* @JoinTable(name="user_tags")
**/
protected $tags;
/**
* Construct a new user.
*/
public function __construct() {
$this->tags = new \Doctrine\Common\Collections\ArrayCollection();
}
// Getters
public function getId() {
return $this->id;
}
public function getFirstName() {
return $this->firstName;
}
public function getTags() {
return $this->tags;
}
// Setters
public function setFirstName($firstName) {
$this->firstName = $firstName;
}
/**
* Add a tag to a user.
* @param Tag
*/
public function addTag(Tag $tag) {
$tag->addUser($this);
$this->tags[] = $tag;
}
}
这是我的标签:
<?php
namespace Project\Model;
/**
* @Entity
* @Table(name="tags")
**/
class Tag implements \JsonSerializable {
/** @Id @Column(type="integer") @GeneratedValue **/
protected $id;
/** @Column(type="string") **/
protected $tag;
/**
* @ManyToMany(targetEntity="Project\Model\User", mappedBy="tags")
*/
protected $users;
public function __construct() {
$this->users = new \Doctrine\Common\Collections\ArrayCollection();
}
// Getters
public function getId() {
return $this->id;
}
public function getTag() {
return $this->tag;
}
// Setters
public function setTag($tag) {
$this->tag = $tag;
}
public function addUser(User $user) {
$this->users[] = $user;
}
}
如果我创建一个新的标签,新的用户,标签添加到用户,然后调用getTag ()方法,它什么都不返回 - 任何人都可以帮我解决我出错的地方吗?
$tag = new Tag();
$tag->setTag('Foo');
$entityManager->persist($tag);
$user = new User();
$user->addTag($tag);
$entityManager->persist($user);
$entityManger->flush();
var_dump($user->getTags());
我已更新我的问题以包含我的命名空间。另外我没有使用Symfony。我应该在哪里获得mappedBy? – JeremyKirkham
要么删除你的“inverdedBy”映射,并且你的实体之间有一个单向关系,要么向你的标记实体添加一个$ users属性,注释为:@ManyToMany(targetEntity =“Project \ Model \ User”,inversedBy = “tags”)' 然后它变成双向的。 –
我与第二个选项,但它仍然没有工作。另外根据教义文档,标记实体注释应该被映射,而不是反向。我试过了,但也没有奏效。 – JeremyKirkham