简体   繁体   English

Symfony2 querybuilder join 在 Sonata bundle 中无法用于 join

[英]Symfony2 querybuilder join not working in Sonata bundle for join

I'm trying to create a simple form with sonata bundle.我正在尝试使用奏鸣曲包创建一个简单的表单。 I have one problem trying to load data entity type field.我在尝试加载数据实体类型字段时遇到一个问题。 I know this is working:我知道这是有效的:

$formMapper->add( 'foo', 'entity', array(
    'class'         => 'myVendorMyBundleBundle:Foo',
    'property'      => 'id',
    'query_builder' => function(FooRepository $er) {
        return $er->createQueryBuilder('qb')
        ->add( 'select', 'f' )
        ->add( 'from', 'myVendorMyBundleBundle:Foo f' )
    },
'label'         => 'foo'
) );                

The problem is I don't want to show entity id, I want to show its name, which is in a related table.问题是我不想显示实体 id,我想显示它的名称,它在相关表中。 I tried to use join statement at createQueryBuilder method, but I didn't get it to work:我试图在 createQueryBuilder 方法中使用 join 语句,但我没有让它工作:

$formMapper->add( 'foo', 'entity', array(
    'class'         => 'myVendorMyBundleBundle:Foo',
    'property'      => 'b.name',
    'query_builder' => function(FooRepository $er) {
        return $er->createQueryBuilder('qb')
        ->add( 'select', 'f' )
        ->add( 'from', 'myVendorMyBundleBundle:Foo f' )
        ->add( 'join', 'myVendorMyBundleBundle:Bar b' )
    },
'label'         => 'foo'
) );                

How can I do this?我怎样才能做到这一点?

You should make a __toString() method on the entity you are using, Symfony will automatically use that as the label.你应该在你使用的实体上创建一个__toString()方法,Symfony 会自动使用它作为标签。

Edit: In your myVendorMyBundleBundle:Foo class you should have a variable $bar defined编辑:在您的myVendorMyBundleBundle:Foo类中,您应该定义一个变量$bar

<?php

// ../app/src/myVendor/MyBundleBundle/Entity/Foo.php

public function __toString()
{
    // If relationship is many to one or one to one
    return $this->bar->getSomeProperty();

    //If relationship is one to many or many to many
    $return_var = '';
    foreach($this->bars as $bar)
    {
        $return_var .= $bar->getSomeProperty() . ' ';
    }

    return $return_var
}

Doctrine will lazy load in the association (not an issue if you are working with a low/singular number of labels)...I have used this method effectively to do what you are describing Doctrine 将在关联中延迟加载(如果您使用的标签数量很少/单数,则不是问题)......我已经有效地使用了这种方法来完成您所描述的工作

<?php
$b->add('foo', 'entity', array(
     'class' => 'myVendorMyBundleBundle:Foo',
));       

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM