从Symfony2中的两个表中选择

时间:2022-10-16 15:18:00

I am making a query inside a form.

我正在表单中进行查询。

The idea is : Now I have a dropdown with all the users, ok?

我的想法是:现在我有一个所有用户的下拉菜单,好吗?

I have a query like this:

我有这样一个问题:

'query_builder' => function(EntityRepository $er) {
      return $er->createQueryBuilder('u')->orderBy('u.lastName', 'ASC');
     }

This works flawless!

这是完美的!

Instead of displaying all the users, I only need the users that are associated with a category. This definition is in the "user_data" table (user_id + category_id).

我不需要显示所有的用户,我只需要与一个类别相关联的用户。这个定义在“user_data”表中(user_id + category_id)。

So, I need to do something like:

所以,我需要做一些事情:

SELECT * FROM users 
WHERE user_id IN (SELECT user_id FROM user_data WHERE category_id='2')

I don't have any entity that looks like UserData, I only have User.php, but inside this file I found this:

我没有任何实体看起来像UserData,我只有User。php,但在这个文件中,我发现:

/**
     *@ORM\ManyToMany(targetEntity="My\Bundle\Entity\Data", inversedBy="users")
     *@ORM\joinTable(name="user_data")
     */
    protected $datas;

[...]

So I see that a relationship is build, but I don't get it how to use it in order to build my query based on the 2 tables...

因此我看到一个关系是构建的,但是我不知道如何使用它来基于这两个表来构建我的查询……

Anyone can help me with this issue? :)

有人能在这个问题上帮助我吗?:)

Thanks!

谢谢!

1 个解决方案

#1


3  

Try this,

试试这个,

'query_builder' => function(EntityRepository $er) {
    return $er->createQueryBuilder('u')
              ->innerJoin('u.datas', 'd')
              ->where('d.category = :category') // Check your Data entity to get the right field name
              ->setParameter('category', $yourCategoryId) // you could use options here
              ->orderBy('u.lastName', 'ASC');
     }

Also, update your question with all your entities (Data, ...)

同时,用你所有的实体更新你的问题(数据,…)

#1


3  

Try this,

试试这个,

'query_builder' => function(EntityRepository $er) {
    return $er->createQueryBuilder('u')
              ->innerJoin('u.datas', 'd')
              ->where('d.category = :category') // Check your Data entity to get the right field name
              ->setParameter('category', $yourCategoryId) // you could use options here
              ->orderBy('u.lastName', 'ASC');
     }

Also, update your question with all your entities (Data, ...)

同时,用你所有的实体更新你的问题(数据,…)