2011-11-29 105 views
1

我这是相互关联的两个型号:主键+外键与重复输入错误

/** @Entity @Table(name="permissions") */ 
class Permissions { 
    /** 
    * @Id @GeneratedValue @Column(type="integer") 
    * @var integer 
    */ 
    protected $id; 

    /** 
    * @Column(type="string") 
    * @var string 
    */ 
    protected $name; 

    public function getId() { return $this->id; } 

    public function setName($name) { $this->name = $name; } 
    public function getName() { return $this->name; } 
} 

/** @Entity @Table(name="permissions_types") */ 
class PermissionsTypes { 
    /** 
    * @Id 
    * @OneToOne(targetEntity="Permissions") 
    * @JoinColumn(name="perm_id", referencedColumnName="id") 
    */ 
    protected $perm; 

    /** 
    * @Id 
    * @Column(type="integer") 
    * @var string 
    */ 
    protected $type; 

    /** 
    * @Column(type="string") 
    * @var string 
    */ 
    protected $name; 

    public function setType($type) { $this->type = $type; } 
    public function getType() { return $this->type; } 

    public function setName($name) { $this->name = $name; } 
    public function getName() { return $this->name; } 
} 

当我想要添加到PermissionsTypes两个实体与值:

perm | type | name 
------------------- 
    1 | 0 | test1 
    1 | 1 | test2 

我得到

Duplicate entry '1' for key 'UNIQ_12CF91AFFA6311EF'

错误的第1列。我做错了什么?

+0

你可以为PermissionsTypes表做一个'show create table table_name'吗?看起来你在perm列上有一个唯一的键,当它应该跨越perm和type。 –

+0

是的,我在这个专栏有独特的关键。问题是,它是如何创造的? –

+0

你是如何创建表格模式的?是手动还是自动生成? –

回答

1

几个问题在这里...

  1. 不能使用相关实体的另一实体的主键(@Id
  2. 您使用的是一到一个关系,但希望每Permissions增加一个以上PermissionTypes。这需要一个多对多关联,最好是双向的。

Permissions添加类型的

/** 
* @OneToMany(targetEntity="PermissionTypes", mappedBy="perm") 
*/ 
protected $types; 

public function __construct() 
{ 
    $this->types = new \Doctrine\Common\Collections\ArrayCollection; 
    // see http://www.doctrine-project.org/docs/orm/2.1/en/reference/association-mapping.html#collections 
} 

,改变PermissionTypes

class PermissionsTypes { 

    /** 
    * @Id @GeneratedValue 
    * @Column(type="integer") 
    */ 
    protected $id; 

    /** 
    * @ManyToOne(targetEntity="Permissions", inversedBy="types") 
    * @JoinColumn(name="perm_id", referencedColumnName="id") 
    */ 
    protected $perm; 

您应仔细阅读本手册的Association Mapping部分。

+0

中有所描述1.我不明白它。你能更精确地解释一下吗? 2.我将“一对一”改为“一对一”,它的效果:)。 –

+0

有错误:[Doctrine \ Common \ Annotations \ AnnotationException] [Syntax Error] Expected Doctrine \ Common \ Annotations \ DocLexer :: T_CLOSE_PARENTHESIS,在属性Permissions :: $类型的位置43处得到'mappedBy'。 –

+0

@KrzysztofTrzos我错过了注释映射中的一些逗号,请参阅我的更新回答 – Phil