oneToMany 关系实体不保存 id 字段 [英] oneToMany relation entity does not save id field
问题描述
我正在尝试使用 奏鸣曲管理
实际上,我希望像 sonata media bundle
与 gallery > 那样有 manyToMany 关系.媒体
Actually I'd like to have manyToMany relation like sonata media bundle
has with gallery > media
一个 HomePage
有很多 Story
应该是可排序的等等.
还有 HomePageStory
来管理关系,如下所示:
https://github.com/sonata-project/SonataAdminBundle/issues/1231
A HomePage
has many Story
s which should be sortable etc.
Theres also HomePageStory
to manage the relation, as suggested here:
https://github.com/sonata-project/SonataAdminBundle/issues/1231
HomePage.orm.yml
oneToMany:
HomePageStorys:
targetEntity: HomePageStory
mappedBy: HomePage
cascade: ["persist", "merge", "remove"]
HomePageAdmin.php
->add(
'HomePageStorys',
'sonata_type_collection',
array(
'cascade_validation' => true,
),
array(
'edit' => 'inline',
'inline' => 'table',
'sortable' => 'position'
)
);
HomePageStory.orm.yml
manyToOne:
HomePage:
targetEntity: HomePage
joinColumn:
name: homepage_id
referencedColumnName: id
Story:
targetEntity: Story
joinColumn:
name: story_id
referencedColumnName: id
HomePageStoryAdmin
protected function configureFormFields(FormMapper $formMapper)
{
$link_parameters = array();
if ($this->hasParentFieldDescription()) {
$link_parameters = $this->getParentFieldDescription()->getOption('link_parameters', array());
}
if ($this->hasRequest()) {
$context = $this->getRequest()->get('context', null);
if (null !== $context) {
$link_parameters['context'] = $context;
}
}
$formMapper
->add(
'Story',
'sonata_type_model_list',
array('required' => false),
array(
'link_parameters' => $link_parameters
)
)
->add('position', 'hidden');
}
到目前为止效果很好,因为我可以在 HomePage Admin 上添加 HomePageStories 并从内联列表中选择一个故事.
This works fine so far, as i can add HomePageStories on the HomePage Admin and pick a Story from the list inline.
但是它只是将story_id
存储在数据库中,而homepage_id
保持为空.如果我手动设置 homepage_id,它会显示在主页管理中.
But it just stores the story_id
in the database while homepage_id
stays empty. If I set the homepage_id by hand, it's displayed in the homepage admin.
知道我需要做什么才能在保存时存储父实体 (HomePage) 的 id 吗?
Any clue what I need to do to store the id of the parent entity (HomePage) on save?
推荐答案
hm,好像你必须手动设置相关子项上的父实体...
hm, seems as if you manually have to set the parent entity on the related children...
虽然不确定是否真的有必要或官方方式",但以下方法奏效了:
While not sure if it is really necessary or "the official way", the following did the trick:
HomePageAdmin.php
public function prePersist($homepage)
{
foreach ($homepage->getHomePageStorys() as $homepagestory) {
$homepagestory->setHomePage($homepage);
}
}
/**
* {@inheritdoc}
*/
public function preUpdate($homepage)
{
foreach ($homepage->getHomePageStorys() as $homepagestory) {
$homepagestory->setHomePage($homepage);
}
}
这篇关于oneToMany 关系实体不保存 id 字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!