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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵