Symfony 2:无法将用户实体作为其所有者添加到项目实体

Symfony 2: cannot add a User-Entity to a Item-Entity as it's owner

我正在尝试项目添加一个用户,因为它是所有者

FormType 中定义的所有内容都会按应有的方式保存,但 owner_idNULL。我没有收到任何错误消息。

有什么想法吗?下面的代码。

提前致谢!

# src/myBundle/Controller/myController.php
class myController extends Controller {
    public function myAction(Request $request) {
        $item = new Item();
        $item->setOwner($this->getUser());

        // print_r($this->getUser());  <- prints a valid user

        $form = $this->createForm(new ItemFormType(), $item);
        if ($request->isMethod('POST')) {
            $form->handleRequest($request);

            if ($form->isValid()) {
                $em = $this->get('doctrine.orm.default_entity_manager');
                $em->persist($item); // saves everything but the owner
                $em->flush();
            }
        }

        return $this->render('myBundle:path/to:template.html.twig', array(
            'form' => $form
        )
    }
}

-

# src/myBundle/Form/ItemFormType.php
class ItemFormType extends AbstractType {
    public function buildForm(FormBuilderInterface $builder, array $options) {            
        $builder->add(...);
        // ...
    }
}

public function configureOptions(OptionsResolver $resolver) {
    $resolver->setDefaults(array(
        'data_class' => 'myBundle\Entity\Item'
    ));
}

public function getName() {
    return 'myItemForm';
}

-

# src/myBundle/Entity/Item.php
class Item {
     // ...
     /**
      * @ORM\ManyToOne(targetEntity="myBundle\Entity\User")
      * @ORM\JoinColumn(name="owner_id", referencedColumnName="id")
      */
    protected $owner;

     // ...
     // Getter & Setter
     // ...     
}

-

# src/myBundle/Entity/User.php
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="fos_user")
 */
class User extends BaseUser {
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * @return mixed
     */
    public function getId()
    {
        return $this->id;
    }
}

问题已解决。不幸的是,我在复制和粘贴 $owner 后没有更改 $deletedBycolumn-name。结果:$deletedBy 用空值覆盖了 $owner

# src/myBundle/Entity/Item.php
class Item {
     // ...
     /**
      * @ORM\ManyToOne(targetEntity="myBundle\Entity\User")
      * @ORM\JoinColumn(name="owner_id", referencedColumnName="id")
      */
    protected $owner;

    // many more

    /**
      * @ORM\ManyToOne(targetEntity="myBundle\Entity\User")
      * @ORM\JoinColumn(name="owner_id", referencedColumnName="id") <- "owner_id"
      */
    protected $deletedBy;

    // ...
    // Getter & Setter
    // ...     
}