我在User和Token之间有关系。我想创建新的令牌并添加到用户的集合。令牌已保存但不是用户ID。
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);
Doctrine throw exception:完整性约束违规:1048列'user_id'不能为null 怎么了?为什么doctrine不会自动设置user_id字段?
答案 0 :(得分:0)
您的令牌是该关系的拥有方。这意味着,在数据库中,它包含外键列(在本例中为user_id
)。
最基本的解决方法是将$user->addToken($token)
替换为$token->setUser($user)
。
如果要在示例中使用该样式,可以通过在UserEntity :: addToken()方法内的令牌上设置用户来实现:
public function addToken(TokenEntity $token)
{
$token->setUser($this); // <--- This is key
$this->tokens->add($token);
}