diff --git a/composer.json b/composer.json index 2c0ad92..fe94cde 100644 --- a/composer.json +++ b/composer.json @@ -1,5 +1,5 @@ { - "name": "elasticquent/elasticquent", + "name": "mendicm/elasticquent", "type": "library", "description": "Maps Laravel Eloquent models to Elasticsearch types.", "keywords": [ @@ -20,7 +20,7 @@ "php": ">=5.4.0", "illuminate/database": "~4.2|^5", "illuminate/config": "~4.2|^5", - "nesbot/carbon": "~1.0", + "nesbot/carbon": "~1.0|^2", "elasticsearch/elasticsearch": "~6.0" }, "require-dev": { diff --git a/src/ElasticquentTrait.php b/src/ElasticquentTrait.php index de56e32..df765a5 100644 --- a/src/ElasticquentTrait.php +++ b/src/ElasticquentTrait.php @@ -5,6 +5,7 @@ use Exception; use ReflectionMethod; use Illuminate\Database\Eloquent\Model; +use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Relations\Relation; /** @@ -706,7 +707,7 @@ public static function loadRelationsAttributesRecursive(Model $model) $reflection_method = new ReflectionMethod($model, $key); // Check if method class has or inherits Illuminate\Database\Eloquent\Model - if(!static::isClassInClass("Illuminate\Database\Eloquent\Model", $reflection_method->class)) { + if(static::isClassInClass("Illuminate\Database\Eloquent\Model", $reflection_method->class)) { $relation = $model->$key(); if ($relation instanceof Relation) { @@ -720,6 +721,12 @@ public static function loadRelationsAttributesRecursive(Model $model) // Unset attribute before match relation unset($model[$key]); $relation->match([$model], $models, $key); + + // The match method doesn't set the relation as loaded if the $models collection is empty + // Set the relation as loaded manually and avoid future database queries + if ((count($value) == 1 && reset($value) === null) || empty($value)) { + $model->setRelation($key, empty($value) ? new Collection() : null); + } } } } @@ -737,7 +744,7 @@ public static function loadPivotAttribute(Model $model, Relation $parentRelation $attributes = $model->getAttributes(); foreach ($attributes as $key => $value) { - if ($key === 'pivot') { + if ($key === 'pivot' && $parentRelation) { unset($model[$key]); $pivot = $parentRelation->newExistingPivot($value); $model->setRelation($key, $pivot);