I have a model called Document
, in this I have a method that I use throughout my website to get the full path to the specific document:
public function getDocument($documentName = true)
{
$documentName = $documentName ? $this->name : null;
return storage_path('app/' . $this->getPath() . $documentName);
}
public function getPath()
{
return "{$this->stream->token}/{$this->unique_id}/";
}
I use it like this (example):
$documentPath = $this->document->getDocument();
However, as you can see, the document path is made up of:
$this->stream->token/$this->unique_id/
Where $this->stream->token
is calling a relationship in my Document model.
public function stream()
{
return $this->belongsTo(Stream::class);
}
Now the method works - I can use the getDocument()
to get the full path to the actual file (or just the folder, if I pass in false
).
However, this code is called from multiple places at different times - and because the folder structure is dependent on the stream_token
, it makes a query to get the associated stream on each request.
Solution(s)?
I have tried adding a $with = ['stream']
property to my Document model, so the associated stream is always loaded when fetching the model - but this I don't believe is a good option either, since then all the other queries I have for the document model, that don't care about the stream property make an extra query.
What else can I do to improve the method and keep the # of queries to the database to a minimum?