Symfony/Doctrine - 从实体构造函数获取记录?
Symfony/Doctrine - Get record from entity constructor?
使用 Symfony 4,我正在查看 choicetype here 的文档,我看到了这个
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'),
],
我假设通过调用 new Category('Cat1')
它基本上会根据名称字段之类的内容在数据库中查找该记录。
如何在 Entity 构造函数中执行此操作?不幸的是,我没有看到任何关于如何做到这一点的文件?或者它只是在那里创建一个新类别(尽管我看不出它是如何工作的,因为它会在不查找的情况下丢失数据库 ID)?
基本上我有以下几点:
Employee Table
- employee_id
Employee Roles Table
- employee_id
- role_id
Roles Table
- role_id
所以一个员工可以担任多个角色。我使用映射 table 来执行此操作。我需要的是一个 choicetype 给我所有的角色(角色 table 中的所有记录),然后选择在映射 table 中找到的角色(员工角色 employee_id = x )
您搜索的可能是https://symfony.com/doc/current/reference/forms/types/entity.html
EntityType
确实从数据库中获取记录(学说)。您可以使用 query_builder
选项根据您的需要修改查询:
https://symfony.com/doc/current/reference/forms/types/entity.html#query-builder
如果您想将选择限制为活动选项,它将看起来像这样(示例):
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');
},
));
使用 Symfony 4,我正在查看 choicetype here 的文档,我看到了这个
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'),
],
我假设通过调用 new Category('Cat1')
它基本上会根据名称字段之类的内容在数据库中查找该记录。
如何在 Entity 构造函数中执行此操作?不幸的是,我没有看到任何关于如何做到这一点的文件?或者它只是在那里创建一个新类别(尽管我看不出它是如何工作的,因为它会在不查找的情况下丢失数据库 ID)?
基本上我有以下几点:
Employee Table
- employee_id
Employee Roles Table
- employee_id
- role_id
Roles Table
- role_id
所以一个员工可以担任多个角色。我使用映射 table 来执行此操作。我需要的是一个 choicetype 给我所有的角色(角色 table 中的所有记录),然后选择在映射 table 中找到的角色(员工角色 employee_id = x )
您搜索的可能是https://symfony.com/doc/current/reference/forms/types/entity.html
EntityType
确实从数据库中获取记录(学说)。您可以使用 query_builder
选项根据您的需要修改查询:
https://symfony.com/doc/current/reference/forms/types/entity.html#query-builder
如果您想将选择限制为活动选项,它将看起来像这样(示例):
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');
},
));