vlucas/spot2 — pull request #54 by Savageman (2014-12-17 13:48:43+00:00)
Title: Set relations on entities when eagerLoading, even when the entity has no related objects

I'll try to describe the problem I've been running into as clearly as possible. It's not so easy, but I'll do my best:

1. Load a Collection of Post entities with their tags `$posts->all()->with(['tags']);`
2. Internally, Spot calls `Mapper->collection()` to create the Collection then calls `Mapper->with` to load the requested relations. Then this happens (I'm only putting the critical path):

```php
$singleEntity = $collection->first();
$relationObject = $singleEntity->relation($relationName);
$relationObject->eagerLoadOnCollection($relationName, $collection);
```

And then inside **eagerLoadOnCollection()**:

```
// Set relation collections back on each entity object
foreach ($collection as $entity) {
if (isset($entityRelations[$entity->$relationEntityKey])) {
$entity->relation($relationName, $entityRelations[$entity->$relationEntityKey]);
}
}
```

So Spot uses the RelationAbstract object from the first entity in the Collection. It then loads all the related entities and assign them into each entity from the collection, but **only for entities which have related objects**.

The problem is that if the **first** Post from the Collection doesn't have any **tags**, then doing `foreach ($firstPost->tags as $tag)` will call `execute()` method the RelationAbstract object. But since it's the first post, its RelationAbstract has been used to load all the related entities from the previous collection. The execute() reuses the same query and **all the tags** from all the posts in the collection **gets assigned to this first post**.

The pull-requests forces the Relation to be populated with an empty Collection or `false` for single relations (hasOne and BelongsTo) to prevent this issue.