Laravel MongoDB中如何删除EmbedOne关联的文档?
如何删除Laravel MongoDB的EmbedsOne关联?
使用laravel-mongodb包实现EmbedsOne关联后,存储TextLock关联正常,但尝试多种方式都无法删除该关联,具体情况如下:
模型代码
use MongoDB\Laravel\Eloquent\Model; use MongoDB\Laravel\Relations\EmbedsOne; class TextContent extends Model { public function lock(): EmbedsOne { return $this->embedsOne(TextLock::class); } } class TextLock extends Model { }
存储关联的代码
$lock = new TextLock(); $textContent->lock()->associate($lock); $textContent->save();
尝试过的无效操作
- 调用关联模型的delete方法:
$textContent->lock->delete(); $textContent->save(); // 无效,$textContent->lock仍存在 // 异常情况:操作后$textContent->lock新增'lock'属性,变为`{lock: null}`
- 调用关联关系的delete方法:
$textContent->lock()->delete(); // 报错:MongoDB\Laravel\Relations\EmbedsOne::delete(): Return value must be of type int, true returned
- 直接将关联属性设为null:
$textContent->lock = null; $textContent->save(); // 无效,$textContent->lock仍存在
可行解决方案
针对laravel-mongodb的EmbedsOne关联删除,推荐以下几种有效方式:
方式一:使用dissociate方法
这是官方推荐的关联移除方式,会直接从父文档中删除嵌入的关联文档:
$textContent->lock()->dissociate(); $textContent->save();
方式二:手动设置属性并标记更新
通过setAttribute方法直接设置关联字段为null,确保模型识别到字段变更:
$textContent->setAttribute('lock', null); $textContent->save();
方式三:使用查询构造器直接更新
通过查询构造器执行unset操作,直接从MongoDB文档中移除该字段:
TextContent::where('_id', $textContent->_id)->unset('lock');
内容的提问来源于stack exchange,提问作者flappix
相关产品推荐
相关产品推荐

