11<?php
22namespace Mongolid \Model ;
33
4+ use Illuminate \Contracts \Container \BindingResolutionException ;
45use Illuminate \Support \Str ;
56use MongoDB \BSON \ObjectId ;
67use Mongolid \Container \Container ;
1415use Mongolid \Schema \Schema ;
1516use Mongolid \Util \CacheComponentInterface ;
1617use Mongolid \Util \ObjectIdUtils ;
18+ use MongolidLaravel \MongolidModel ;
1719
1820/**
1921 * It is supposed to be used on model classes in general.
@@ -25,11 +27,12 @@ trait HasLegacyRelationsTrait
2527 /**
2628 * Returns the referenced documents as objects.
2729 *
28- * @param string $entity class of the entity or of the schema of the entity
29- * @param string $field the field where the _id is stored
30- * @param bool $cacheable retrieves a CacheableCursor instead
30+ * @param string $entity class of the entity or of the schema of the entity
31+ * @param string $field the field where the _id is stored
32+ * @param bool $cacheable retrieves a CacheableCursor instead
3133 *
3234 * @return mixed
35+ * @throws BindingResolutionException
3336 */
3437 protected function referencesOne (string $ entity , string $ field , bool $ cacheable = true )
3538 {
@@ -41,14 +44,7 @@ protected function referencesOne(string $entity, string $field, bool $cacheable
4144
4245 $ entityInstance = Container::make ($ entity );
4346
44- /** @var CacheComponentInterface $cacheComponent */
45- $ cacheComponent = Container::make (CacheComponentInterface::class);
46- $ cacheKey = $ this ->generateCacheKey ($ entityInstance , $ referencedId );
47-
48- // Checks if the model was already eager loaded.
49- // if so, we don't need to query database to
50- // use the document.
51- if ($ document = $ cacheComponent ->get ($ cacheKey )) {
47+ if ($ cacheable && $ referencedId && $ document = $ this ->getDocumentFromCache ($ entityInstance , $ referencedId )) {
5248 return $ document ;
5349 }
5450
@@ -192,4 +188,24 @@ public function detach(string $field, &$obj)
192188 $ embedder = Container::make (DocumentEmbedder::class);
193189 $ embedder ->detach ($ this , $ field , $ obj );
194190 }
191+
192+ /**
193+ * @return mixed|null
194+ * @throws \Illuminate\Contracts\Container\BindingResolutionException
195+ */
196+ private function getDocumentFromCache (ModelInterface $ entityInstance , string $ referencedId )
197+ {
198+ /** @var CacheComponentInterface $cacheComponent */
199+ $ cacheComponent = Container::make (CacheComponentInterface::class);
200+ $ cacheKey = $ this ->generateCacheKey ($ entityInstance , $ referencedId );
201+
202+ // Checks if the model was already eager loaded.
203+ // if so, we don't need to query database to
204+ // use the document.
205+ if (!$ document = $ cacheComponent ->get ($ cacheKey )) {
206+ return null ;
207+ }
208+
209+ return $ document ;
210+ }
195211}
0 commit comments