我有一个网站,用户可以在其中上传文档。文档已上传到我称为Stream
的位置。每当上传文档时,我都需要创建三个文件夹:
我通过在创建文档时侦听Document.php
模型上的事件来做到这一点。此外,我还预加载了流关系:
protected $with = ['stream'];
protected $dispatchesEvents = [
'created' => DocumentCreated::class, //Once document has been uploaded.
];
public function stream()
{
return $this->belongsTo(Stream::class);
}
我已经在EventServiceProvider
中注册了该活动,如下所示:
DocumentCreated::class => [ProcessUploadedDocument::class]
在我的事件文件DocumentCreated.php
中,我只是这样:
public $document;
[...]
public function __construct($document)
{
$this->document = $document;
}
然后在侦听器类ProcessUploadedDocuments
中,我终于创建了文件夹:
CreateDocumentFolders::dispatch($event->document);
因此,以上工作触发了2个查询:
select * from `streams` where `streams`.`id` in (3)
select * from `documents` where `documents`.`id` = ? limit 1
现在在我的侦听器类中,我想在创建文档时做更多的事情。具体来说,我需要检索与文档上传到的流相关的一些字段。所以我添加了这个:
$fields = $event->document->stream->fields; //Added this <=
CreateDocumentFolders::dispatch($event->document);
在我的Stream
模型中,字段关系为:
public function fields()
{
return $this->hasMany(Field::class);
}
通过将$fields
行添加到我的侦听器中,查询数量已增加到4:
select * from `fields` where `fields`.`stream_id` in (3)
select * from `streams` where `streams`.`id` in (3)
select * from `streams` where `streams`.`id` in (3)
select * from `documents` where `documents`.`id` = ? limit 1
那是为什么?我怀疑只有3个查询,但是以某种方式触发了以下查询两次:
select * from `streams` where `streams`.`id` in (3)