【问题标题】:Default value in Doctrine for in relations columnsDoctrine 中关系列的默认值
【发布时间】:2016-09-22 20:11:55
【问题描述】:

我知道有这个问题Default value in Doctrine

我的问题是,当列具有 ManyToOne 关系时,如何在 Doctrine2/Symfony2 中设置默认值 = 0?

DB 中的product_id 列是not null,我无法更改!

如果我执行 setProductId(0),它会以某种方式被 setProduct(null) 覆盖,然后我得到了。

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

如果我按照doctrine-faqs 的建议默认$product = 0;$productId = 0; 或两者兼而有之,我会得到

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

如果没有设置,我想设置它 = 0!

是否可以,甚至允许 $productId 和 $product 属性指向同一个数据库列?

代码几乎是这样的:

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;
}

【问题讨论】:

  • 为什么不想在注解中添加nullable=true
  • 也许你可以使用 -1 而不是 0 ?
  • @Marius mysql DB 中的列product_id 不为空,无法更改!

标签: php symfony doctrine-orm doctrine


【解决方案1】:

您的问题有两个问题。

首先,您不能让 $product 和 $productId 属性指向同一个数据库列。

您应该只有一个 $product 属性,如果您需要访问产品的 $id 属性,请执行以下操作:

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

其次,要允许数据库列 product_id 接受空值,只需在注释中设置它,就像 Marius 在其评论中所说的那样(之后,不要忘记使用 php app/console doctrine:schema:update 更新数据库)。

所以,你的整个代码应该是这样的:

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;
}
}

【讨论】:

  • 现在有一点很清楚了,谢谢!我们不应该同时拥有 $product 和 $productId ...其他是 product_id 不是 NULL 字段,我不想在那里设置 null ...我希望将默认值设置为 0。抱歉回复晚了...
猜你喜欢
  • 1970-01-01
  • 2011-03-23
  • 1970-01-01
  • 1970-01-01
  • 2011-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多