我正在尝试在doctrine odm中实现这种模式http://cookbook.mongodb.org/patterns/random-attribute/。
我想在pre-persist生命周期事件上设置此属性。为了获得最佳结果,我想使用本机javascript函数Math.random(),因为php无法生成随机浮点数,我想避免为此编写自定义函数。
有没有办法实现这个目标?
我试过了:
/** @PrePersist */
public function generateRandom()
{
$this->random = new \MongoCode('Math.random()');
}
但它总是将属性设置为1,无论函数的代码是什么
答案 0 :(得分:-1)
我不确定这是最好的解决方案,但它对我有用:
/**
* @MongoDB\PrePersist()
* @MongoDB\PreUpdate()
*/
public function generateRandom() {
$this->random = rand();
}