我有一個帶有多個自繼承的 EmbeddedDocument 的檔案類。它作業正常,但是當我不發送 subData 時,它作為空陣列 (subData: []) 保存在 Mongo 中。
如果不發送,我希望這個欄位根本不會保存。
我試過nullable=false和nullable=true。
不在 __construct 中設定 ArrayCollection 會出錯Call to a member function add() on null
- 交響樂 4.3
- 學說/mongodb 1.6.4
- 學說/mongodb-odm 1.3.7
- 學說/mongodb-odm-bundle 3.6.2
<?php
namespace App\Document;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
/**
* @MongoDB\EmbeddedDocument()
*/
class Data
{
/**
* @MongoDB\Id()
*/
private $id;
/**
* @MongoDB\Field(type="string")
*/
private $value;
/**
* @MongoDB\EmbedMany(targetDocument="App\Document\Data", nullable=false)
*/
public $subData = null;
public function __construct()
{
$this->subData = new ArrayCollection();
}
public function getId(): ?string
{
return $this->id;
}
public function getValue(): ?string
{
return $this->value;
}
public function setValue(string $value): self
{
$this->value = $value;
return $this;
}
public function getSubData(): Collection
{
return $this->subData;
}
public function setSubData(array $subData): self
{
$this->subData = $subData;
return $this;
}
public function addSubdata(Data $subData): self
{
$this->subData->add($subData);
return $this;
}
}
更新
將 setter 更改為此并沒有像@Maniax 所建議的那樣幫助它仍然是subData: []
public function setSubData(array $subData): self
{
if(!empty($subData) && count($subData) > 0 && $subData !== null) {
$this->subData = $subData;
}
return $this;
}
uj5u.com熱心網友回復:
如果你不想在陣列為空時在你的資料庫中使用 null,你希望避免默認初始化它,所以避免
public function __construct()
{
$this->subData = new ArrayCollection();
}
該陣列仍然需要初始化,因此在添加函式中,您必須在添加之前檢查陣列是否未初始化
public function addSubData(Data $subData): self
{
// null and an empty array are falsey
if (!$this->subData) {
$this->subData = new ArrayCollection();
}
$this->subData->add($subData);
}
return $this;
}
在 setter 中你檢查你是否沒有得到一個空陣列
public function setSubData(array $subData): self
{
if(!empty($subData)) {
$this->subData = $subData;
}
return $this;
}
這應該可以防止空陣列最終出現在您的資料庫中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/533878.html
