Symfony2学说ManyToMany关系 [英] Symfony2 doctrine ManyToMany relation

查看:119
本文介绍了Symfony2学说ManyToMany关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Synfony2和教义用法的初学者。我创建了两个实体,如下所示:

I'm a beginner on Synfony2 and doctrine usage. I've created two entities as following :

对于最终用户实体(扩展名FOSUserBundle):

For EndUser Entity (extension of FOSUserBundle ):

/**
 * EndUser
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="Core\CustomerBundle\Entity\EndUserRepository")
 */
class EndUser extends BaseUser {
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\ManyToMany(targetEntity="Core\GeneralBundle\Entity\Discipline", mappedBy="endusers")
     */
    private $discipline;

对于学科实体

class Discipline {
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\ManyToMany(targetEntity="Core\CustomerBundle\Entity\EndUser", inversedBy="discipline")
     */
    private $endusers;

当我这样做 php应用程序/控制台学说:schema:update-强制

最终用户纪律 discipline_enduser 表已创建。

当我通过phpmyadmin运行标准SQL请求时: / p>

When I run a standard SQL request through phpmyadmin as :

select t0.*
from
discipline t0,
discipline_enduser t2
where 
t2.enduser_id = 1
and 
t2.discipline_id = t0.id

我获得了预期结果作为特定用户的学科列表。

I obtain the expected result as the list of discipline for a specific user.

我关心的是如何使用带有Symfony2&Doctrine的实体来实现相同的目标

My concern is how to implement the same using the Entity with Symfony2 & Doctrine

推荐答案

首先,我建议为您的关系使用更自然的语言名称,例如学科 endUsers ,因为它是 manyToMany 债券。此外,您还需要创建 get set 的方法啊在为实体准备好所有属性之后,应运行命令生成您的getter和setters

First I would recommend to use more natural language names for you relationships, like disciplines and endUsers since it is a manyToMany bond. Also, you need to create the get and set method for each. After you have prepared all your properties for an entity you should run the command to Generate your getters and setters

//this will generate all entities
php app/console doctrine:generate:entities BundleNamespace

之后,您可以执行以下操作:

After that, you can do things like :

$endUser->getDisciplines(); //return all disciplines of this user
$endUser->addDiscipline($someDiscipline); //add another discipline
$endUser->removeDiscipline($iAmABadDiscipline); //remove this discipline from this user
array $disciplines = [ ... ];
$endUser->setDisciplines($disciplines); // set multiple disciplines

学科实体,当然应该使用 EntityManager 更新它们,您可以在答案此处

Same logic applies to Discipline entity, ofcourse you should update them with an EntityManager for which you can read more in the answer here.

这篇关于Symfony2学说ManyToMany关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆