我想将 JJ/MM/YYYY 格式的日期存储到关联数组中,如下所示:
'day' => $day,
'month' => $month,
'year' => $year
我很容易做到这一点,但是一旦我尝试将文档存储在集合中,日期就会存储在文档中,如下所示:
0 => $day
1 => $month
2 => $year
我在“刷新”之前对对象进行了 PHP 调试,它显示了与值关联的键,但一旦进入集合,它就被数字键重置了。
我的实体如下所示:
/**
* @MongoDB\Field(type="collection")
*/
private $date;
public function getDate()
{
return $this->date;
}
public function setDate($date)
{
$this->date = $date;
return $this;
}
Controller 部分:
$date = $movie->getDate();
$keys = array('day', 'month', 'year');
$values = explode('/', $date);
$dateArray = array_combine($keys, $values);
$movie->setDate($dateArray);
我想准确地说,我正在 Symfony 4 上使用 Doctrine ODM for MongoDB。
这是我的问题:
1)如何存储具有关联键的数组?
2) MongoDB 文档中的键是否“固定”?我的意思是,我确定键 0 始终与 $day 关联,键 1 始终与 $month 关联吗?
最佳答案
您需要使用哈希
type :
hash
: associative array to MongoDB object
collection
: numerically indexed array to MongoDB array
/**
* @MongoDB\Field(type="hash")
*/
private $date;
关于php - 为什么我不能在 MongoDB 文档中存储关联数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56228941/