doqp87012 2018-09-25 04:15
浏览 46
已采纳

Symfony / Doctrine - 从实体构造函数中获取记录?

Using Symfony 4, I'm looking at the documentation for choicetype here and I see this

use App\Entity\Category;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
// ...

$builder->add('category', ChoiceType::class, [
    'choices' => [
        new Category('Cat1'),
        new Category('Cat2'),
        new Category('Cat3'),
        new Category('Cat4'),
    ],

I assume that by calling new Category('Cat1') that it would basically do a lookup in the database of that record based of something like a name field.

How do you do that in the Entity constructor? Unfortunately I don't see any documentation on how that would be done? Or is it just making a new category there (though I fail to see how this would work as it would be missing the database id without a lookup)?

Basically I have the following:

Employee Table
 - employee_id

Employee Roles Table
 - employee_id
 - role_id

Roles Table
 - role_id

So one employee can have many roles. I use a mapping table to do this. What I need is a choicetype that gives me all the roles (all records from Roles table) and then selects the ones that are found in the mapping table (Employee Roles where employee_id = x)

  • 写回答

1条回答 默认 最新

  • douni1396 2018-09-25 05:52
    关注

    What you are searching might be https://symfony.com/doc/current/reference/forms/types/entity.html

    The EntityType does get records from the database (doctrine). You can use the query_builder option to modify the query to your needs: https://symfony.com/doc/current/reference/forms/types/entity.html#query-builder

    It will look like this if you want to limit the choices to active ones (example):

    use App\Entity\Category;
    use Symfony\Bridge\Doctrine\Form\Type\EntityType;
    // ...
    
    $builder->add('category', EntityType::class, array(
        'class' => Category::class,
        'choice_label' => 'displayName', // property to use as the option value
        'query_builder' => function (EntityRepository $er) {
            return $er->createQueryBuilder('c')
                ->where('c.active = 1');
        },
    ));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何对TBSS的结果进行统计学的分析已完成置换检验,如何在最终的TBSS输出结果提取除具体值及如何做进一步相关性分析
  • ¥15 SQL数据库操作问题
  • ¥100 关于lm339比较电路出现的问题
  • ¥15 Matlab安装yalmip和cplex功能安装失败
  • ¥15 加装宝马安卓中控改变开机画面
  • ¥15 STK安装问题问问大家,这种情况应该怎么办
  • ¥15 关于罗技鼠标宏lua文件的问题
  • ¥15 halcon ocr mlp 识别问题
  • ¥15 已知曲线满足正余弦函数,根据其峰值,还原出整条曲线
  • ¥20 无法创建新的堆栈防护界面