|
5 | 5 | namespace MongoDB\Laravel\Eloquent;
|
6 | 6 |
|
7 | 7 | use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
|
| 8 | +use MongoDB\BSON\Document; |
8 | 9 | use MongoDB\Driver\CursorInterface;
|
9 | 10 | use MongoDB\Driver\Exception\WriteException;
|
10 | 11 | use MongoDB\Laravel\Connection;
|
|
16 | 17 | use function array_merge;
|
17 | 18 | use function collect;
|
18 | 19 | use function is_array;
|
| 20 | +use function is_object; |
19 | 21 | use function iterator_to_array;
|
| 22 | +use function property_exists; |
20 | 23 |
|
21 | 24 | /** @method \MongoDB\Laravel\Query\Builder toBase() */
|
22 | 25 | class Builder extends EloquentBuilder
|
@@ -178,21 +181,26 @@ public function raw($value = null)
|
178 | 181 |
|
179 | 182 | // Convert MongoCursor results to a collection of models.
|
180 | 183 | if ($results instanceof CursorInterface) {
|
181 |
| - $results = iterator_to_array($results, false); |
| 184 | + $results->setTypeMap(['root' => 'array', 'document' => 'array', 'array' => 'array']); |
| 185 | + $results = $this->query->aliasIdForResult(iterator_to_array($results)); |
182 | 186 |
|
183 | 187 | return $this->model->hydrate($results);
|
184 | 188 | }
|
185 | 189 |
|
186 |
| - // Convert MongoDB BSONDocument to a single object. |
187 |
| - if ($results instanceof BSONDocument) { |
188 |
| - $results = $results->getArrayCopy(); |
189 |
| - |
190 |
| - return $this->model->newFromBuilder((array) $results); |
| 190 | + // Convert MongoDB Document to a single object. |
| 191 | + if (is_object($results) && (property_exists($results, '_id') || property_exists($results, 'id'))) { |
| 192 | + $results = (array) match (true) { |
| 193 | + $results instanceof BSONDocument => $results->getArrayCopy(), |
| 194 | + $results instanceof Document => $results->toPHP(['root' => 'array', 'document' => 'array', 'array' => 'array']), |
| 195 | + default => $results, |
| 196 | + }; |
191 | 197 | }
|
192 | 198 |
|
193 | 199 | // The result is a single object.
|
194 |
| - if (is_array($results) && array_key_exists('_id', $results)) { |
195 |
| - return $this->model->newFromBuilder((array) $results); |
| 200 | + if (is_array($results) && (array_key_exists('_id', $results) || array_key_exists('id', $results))) { |
| 201 | + $results = $this->query->aliasIdForResult($results); |
| 202 | + |
| 203 | + return $this->model->newFromBuilder($results); |
196 | 204 | }
|
197 | 205 |
|
198 | 206 | return $results;
|
|
0 commit comments