2016-10-26 41 views
0

我有用戶和令牌之間的關係。我想創建新的令牌並添加到用戶的集合。令牌一直保存但不是用戶標識。Symfony3關係之一許多添加收藏不起作用

AppBundle\UserEntity: 
    type: entity 
    table: null 
    repositoryClass: AppBundle\Repository\UserEntityRepository 
    id: 
     id: 
      type: integer 
      id: true 
      generator: 
       strategy: AUTO 
    fields: 
     username: 
      type: string 
      length: 255 
      unique: true 
     password: 
      type: string 
      length: 255 
      nullable: true 
     salt: 
      type: string 
      length: 255 
      unique: true 
     email: 
      type: string 
      length: '100' 
    lifecycleCallbacks: { } 
    oneToMany: 
     token: 
     targetEntity: TokenEntity 
     mappedBy: user 
     fetch: EAGER 



AppBundle\TokenEntity: 
    type: entity 
    table: null 
    repositoryClass: AppBundle\Repository\TokenEntityRepository 
    id: 
     id: 
      type: integer 
      id: true 
      generator: 
       strategy: AUTO 
    fields: 
     value: 
      type: string 
      length: 255 
      unique: true 
    lifecycleCallbacks: { } 
    manyToOne: 
     user: 
     targetEntity: UserEntity 
     inversedBy: token 
     joinColumns: 
      user_id: 
      referencedColumnName: id 
      nullable: false 

創建新的對象:

$token = new TokenEntity() 
$token->setValue('lorem'); //in token table is field user_id but I want that doctrine set this field auto 


$user = new UserEntity; 
$user->setUsername('example'); 
$user->setPassword('password'); 
$user->addToken($token); 

主義拋出異常:完整性約束違規:1048列 'user_ID的' 不能爲空 有什麼不對?爲什麼學說不會自動設置user_id字段?

+0

如何學說可以設置'user_id'上'TokenEntity'如果用戶不存在? – malcolm

+0

如果用戶對象之前創建的令牌實體也不起作用 – Matrix12

回答

0

您的令牌是擁有方的關係。這意味着,在數據庫中,它包含外鍵列(在本例中爲user_id)。

最基本的解決方法是用$token->setUser($user)替換$user->addToken($token)

如果你想使用的樣式在你的榜樣,您可以通過設置用戶的令牌你UserEntity內這樣做:: addToken()方法:

public function addToken(TokenEntity $token) 
{ 
    $token->setUser($this); // <--- This is key 
    $this->tokens->add($token); 
}