【发布时间】:2017-05-04 10:15:51
【问题描述】:
我正在尝试使用表单将图像 URL 存储到数据库中。
我有 2 个实体:
产品和产品图片。
Product 与 ProductImages 具有 OneToMany 关系,并且 ProductImages 与 Product 具有多对一关系。
产品:
/**
* @ORM\OneToMany(targetEntity="ProductImages", mappedBy="product")
*/
private $images;
/**
* @return mixed
*/
public function getImages()
{
return $this->images;
}
/**
* @param mixed $images
* @return $this
*/
public function setImages($images)
{
$this->images = $images;
return $this;
}
产品图片:
/**
* @ORM\ManyToOne(targetEntity="Product", inversedBy="images")
* @ORM\JoinColumn(nullable=false)
*/
private $product;
/**
* @return mixed
*/
public function getProduct()
{
return $this->product;
}
/**
* @param mixed $product
*/
public function setProduct(Product $product)
{
$this->product = $product;
}
我制作了一个表格,带有文件上传和这个控制器:
$product = new Product();
$form = $this->createForm(ProductFormType::class, $product);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()) {
$file = $product->getImages();
$fileName = $form->get('slug')->getData().'.'.$file->guessExtension();
$file->move(
$this->getParameter('product_image_directory'),
$fileName
);
$product->setImages($fileName);
$em = $this->getDoctrine()->getManager();
$em->persist($product);
$em->flush();
$this->addFlash('success', 'Product aangemaakt!');
return $this->redirectToRoute('admin_product_list');
}
我得到的错误是:
Type error: Argument 1 passed to Doctrine\Common\Collections\ArrayCollection::__construct() must be of the type array, string given, called in C:\git\symfony\vendor\doctrine\orm\lib\Doctrine\ORM\UnitOfWork.php on line 605
我已经尝试将 ProductImages 保存为 new ProductImages(); 并填写所有字段,但这也不起作用。
【问题讨论】:
-
它必须是产品图像数组,您必须传递单个对象而不是对象数组