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 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失