2011-11-29 104 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