gpt4 book ai didi

symfony - 原则 2 将 bool 值设置回 null

转载 作者:行者123 更新时间:2023-12-02 16:48:51 25 4
gpt4 key购买 nike

我有一个带有 boolean 类型的 Doctrine2 实体,使用 mysql 中的tinyint 来存储结果。在初始添加值时,我可以将其设置为 null。如果我将 0 或 1 以外的任何新值保存为 0 或 1,则传入的任何新值都会保存为 0。

下面是具有 get 和 set 方法的变量。我已经完成了 var_dump 来确认该值在保存为 0 之前已设置为 null。

 /**
* @var string $completed
*
* @ORM\Column(name="is_completed", type="boolean", length=1, nullable=true)
* @Api(type="field")
*/
private $completed;

/**
* Set completed
*
* @param boolean $value
*/
public function setCompleted($value = null)
{
if ($value=='') {
$value = null;
}
$this->completed = $value;
}

/**
* Get completed
*
* @return boolean
*/
public function getCompleted()
{
if (is_null($this->completed)) {
$this->completed = '';
}
return $this->completed;
}

最佳答案

试试这个:

public function setCompleted($value = null)
{
if ('' === $value) {
$value = null;
}
$this->completed = $value ? true : false;
}

假设,当传递一个空字符串时,您需要 null,否则根据 的默认 PHP 行为,您需要 truefalse >$值

正如建议的那样, setter/getter 没有副作用!只要您使用上面的 setter,这应该与您的 getCompleted 完全相同:

public function getCompleted()
{
if (null === $this->completed)) {
return '';
}

return $this->completed;
}

关于symfony - 原则 2 将 bool 值设置回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13424680/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com