[英]Why user_id column is NULL?
Im trying to create relation between Products And Users. 我试图在产品和用户之间建立联系。 One User has many Products and Many Products => 1 User. 一个用户拥有许多产品,许多产品=> 1个用户。 The problem is when i add the form to the table "products" column user_id = NULL. 问题是当我将表格添加到表“产品”列中时,user_id = NULL。
Here is my relation in Product Entity: 这是我在产品实体中的关系:
/**
* @ORM\ManyToOne(targetEntity="AppBundle\Entity\User", inversedBy="products")
* @ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
private $user;
And User Entity: 和用户实体:
/**
* @ORM\OneToMany(targetEntity="AppBundle\Entity\Product", mappedBy="user")
*/
private $products;
Why the column user_id is always null? 为什么列user_id始终为null? Here is the code used to persists products. 这是用于保留产品的代码。
/**
* @Route("/products/add", name="create_products")
* @Security("has_role('ROLE_USER') or has_role('ROLE_EDITOR') or has_role('ROLE_ADMIN')")
* @param Request $request
* @return \Symfony\Component\HttpFoundation\Response
*/
public function createProductAction(Request $request)
{
$product = new Product();
$form = $this->createForm(ProductType::class, $product);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()) {
/** @var UploadedFile $file */
$file = $product->getImageForm();
$filename = md5($product->getName());
$file->move(
$this->get('kernel')->getRootDir() . '/../web/images/products/',
$filename
);
$product->setImage($filename);
$em = $this->getDoctrine()->getManager();
$em->persist($product);
$em->flush();
$this->redirectToRoute('products');
return $this->redirectToRoute('products');
}
return $this->render('products/create.product.html.twig', array(
'productForm' => $form->createView()
));
}
You haven't used your setter in your Product object to set your user in your controller. 您尚未使用Product对象中的setter在控制器中设置用户。 That is the problem. 那就是问题所在。
You would need to use the setter like so: 您将需要像这样使用setter:
$product->setImage($filename);
$product->setUser( $user );
$em = $this->getDoctrine()->getManager();
$em->persist($product);
The above presumes you have a setter called setUser
. 以上假设您有一个名为setUser
的设置器。 You also need to create the user or determine the user. 您还需要创建用户或确定用户。
You are persisting a product without a user. 您正在坚持没有用户的产品。 You should do something like this: 您应该执行以下操作:
$product = new Product();
$product->setImage($filename);
$em = $this->getDoctrine()->getManager();
// here you associate the user
$user = $em->find('\AppBundle\Entity\User', 3); // user with id 3
$product->setUser($user);
$em->persist($product);
$em->flush();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.