如何在symfony2 Doctrine2中的构造函数中将实体添加到用户对象

如何在symfony2 Doctrine2中的构造函数中将实体添加到用户对象

问题描述:

I have the user object who has manytomany relation with Group entity.

But i want that by default the user should be added to Group Group_User which has id=4 in database.

Now how can i add that in User constructor

How can use query in Entity class

我的 user code>对象与 Group code有很多关系 > entity。 p>

但是我希望默认情况下应该将用户添加到数据库中id = 4的Group Group_User code>。 p> \ n

现在我如何在用户构造函数中添加它 p>

如何在实体类中使用查询 p> div>

You can pass what you want in your User constructor. You'll have to pass it from your controller (where your queryManger is available).

In your controller:

$group_user = $this->getDoctrine()->getEntityManager()->getRepository("Bundle:Entity")->find(4);
$user = new User($group_user);

In your construct:

public function __construct(Group $group_user)
{
    $this->$group = $group_user;
}

When you'll persist your user entity in the controller, the user and it's group relation will be directly saved.