1

I know there is this question Default value in Doctrine

My question is how do I set a default value=0 in Doctrine2/Symfony2, when column has ManyToOne relation?

Column product_id in DB is not null, I can't change it!

If I do setProductId(0), it is somehow overridden by setProduct(null) and I get.

Integrity constraint violation: 1048 Column 'product_id' cannot be null

If I default $product = 0; or $productId = 0; or both, as suggested by doctrine-faqs, I get

Expected value of type "Entity\Product" ...

I want to set it = 0 if its not set!

Is it OK Or even allowed to have $productId and $product properties pointing to same database column?

Code almost look like this:

class ShopLog {

/**
 * @var integer
 *
 * @ORM\Column(name="product_id", type="integer", nullable=false) // , columnDefinition="DEFAULT 0" does not work
 */
private $productId;

/**
 * @var Entity\Product
 *
 * @ORM\ManyToOne(targetEntity="Entity\Product")
 * @ORM\JoinColumns({
 *   @ORM\JoinColumn(name="product_id", referencedColumnName="id", nullable=false) // , columnDefinition="DEFAULT 0" does not work
 * })
 */
private $product;

/**
 * Set productId
 *
 * @param integer $productId
 * @return ShopLog
 */
public function setProductId($productId)
{

    $this->productId = $productId;

    return $this;
}

/**
 * Set product
 *
 * @param \Entity\Product $product
 * @return ShopLog
 */
public function setProduct(\Entity\Product $product = null)
{
    $this->product = $product;
    return $this;
}
Community
  • 1
  • 1
Shahid
  • 255
  • 6
  • 14

1 Answers1

1

There are two questions in your question.

First, you can't have $product and $productId properties pointing on the same database column.

You should have only a $product property, and if you need to access the $id property of a product, do something like this:

$productId = $shoplog->getProduct()->getId(); 

Second, to allow the database column product_id to accept null values, just set it in the annotation, like Marius said in its comment (and after, don't forget to update the database with php app/console doctrine:schema:update).

So, your whole code should look like:

class ShopLog {

/**
 * @var Entity\Product
 *
 * @ORM\ManyToOne(targetEntity="Entity\Product")
 * @ORM\JoinColumn(name="product_id", referencedColumnName="id", nullable=true)
 * })
 */
private $product;

/**
 * Set product
 *
 * @param \Entity\Product $product
 * @return ShopLog
 */
public function setProduct(\Entity\Product $product = null)
{
    $this->product = $product;
    return $this;
}
}
scandel
  • 1,692
  • 3
  • 20
  • 39
  • 1
    One point is clear now thanks! we should not have both $product and $productId... Other was product_id is NOT NULL field, and i don't want to set null there... I want default value set to 0. sorry for late reply... – Shahid May 30 '16 at 09:51