简体   繁体   中英

Persisting entity with Doctrine association

I'm having trouble trying to persist an entity with an association using Doctrine.

Here's the mapping on my owning side: (User.php)

/** @Role_id @Column(type="integer") nullable=false */
private $role_id;

/** 
 * @ManyToOne(targetEntity="Roles\Entities\Role")
 * @JoinColumn(name="role_id", referencedColumnName="id")
 */
private $role;

There's no mapping on the inverse side, I tried with (OneToMany) and it didn't seem to make a difference.

Basically, I'm passing a default value of 2 (integer) to a method setRole_id but it shows up as blank when I actually go to persist the entity which causes a MySQL error as that column doesn't allow nulls .

Edit 1:

Literally just persisting this for role_id

$this->user->setRole_id( 2 );

Cheers,

Ewan

Your mapping seems incorrect. Try to rewrite it as follows:

/** 
 * @ManyToOne(targetEntity="Roles\Entities\Role")
 * @JoinColumn(name="role_id", referencedColumnName="id", nullable=false)
 */
private $role;

In other words, you only need to describe the role_id as the join column of your relationship. You don't need to map it as a "normal" column. Then just write and use a regular setter declared like the one below:

public function setRole(Roles\Entities\Role $role) {

    $this->role = $role;
}

Use the above instead of $this->user->setRole_id(2) and persist your user entity. Doctrine should automatically take care of storing the correct entity ID in the foreign key field for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM