简体   繁体   中英

how to set column value before persist in symfony2?

Suppose I have to set column value formula to 1. So how can I do it before persisting. After persisting I should get 1 in database.

 $f=1;
 $product->setFormula($f);
 $em->persist($product); 

If I use above line it gives an error

Expected value of type "Nimo\\MrmdBundle\\Entity\\Product" for association field "Nimo\\MrmdBundle\\Entity\\Product#$basedOn", got "integer" instead

Here is entity code

/**
 * @ORM\ManyToOne(targetEntity="Product")
 * @ORM\JoinColumn(name="formula", referencedColumnName="someothercolumn",nullable=true)
 **/
private $formula = null;

You have to correct your entity definition first, However here's what you need to do in your controller. This will not work until you make sure your entities are correctly defined. (I can't because I don't know your entity definitions)

$f=1;
$em = $this->container->get('doctrine.orm.entity_manager');
$repo = $em->getRepository('AppBundle:Formula'); //This should be your referred entity
//You can also do findOneByName below
$formula= $repo->findOneById($id); //This should be the primary key of the referred entity NOT 1
$formula->setFormula($f);
$em->persist($formula);

When you are creating a relationship between two entities you can not pass a single value or variable containing a single value.

Entity works on objects. So try to pass the object of some entity or create an object with some value it will work. I also face the same error while passing a single value. Just pass the Object of an entity relationship annotation will picked up the joining column of other entity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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