Skip to content

Commit 6f0117d

Browse files
committed
Use id as primary key for DocumentModel
1 parent 8bbcdbf commit 6f0117d

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

44 files changed

+371
-393
lines changed

docs/includes/auth/PersonalAccessToken.php

-1
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,5 @@ class PersonalAccessToken extends SanctumToken
1111

1212
protected $connection = 'mongodb';
1313
protected $table = 'personal_access_tokens';
14-
protected $primaryKey = '_id';
1514
protected $keyType = 'string';
1615
}

docs/includes/eloquent-models/PlanetThirdParty.php

-1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,5 @@ class Planet extends CelestialBody
1010
use DocumentModel;
1111

1212
protected $fillable = ['name', 'diameter'];
13-
protected $primaryKey = '_id';
1413
protected $keyType = 'string';
1514
}

docs/includes/fundamentals/write-operations/WriteOperationsTest.php

+9-9
Original file line numberDiff line numberDiff line change
@@ -162,7 +162,7 @@ public function testModelUpdateFluent(): void
162162

163163
// begin model update one fluent
164164
$concert = Concert::where(['performer' => 'Brad Mehldau'])
165-
->orderBy('_id')
165+
->orderBy('id')
166166
->first()
167167
->update(['venue' => 'Manchester Arena', 'ticketsSold' => 9543]);
168168
// end model update one fluent
@@ -370,31 +370,31 @@ public function testModelDeleteById(): void
370370

371371
$data = [
372372
[
373-
'_id' => 'CH-0401242000',
373+
'id' => 'CH-0401242000',
374374
'performer' => 'Mitsuko Uchida',
375375
'venue' => 'Carnegie Hall',
376376
'genres' => ['classical'],
377377
'ticketsSold' => 2121,
378378
'performanceDate' => new UTCDateTime(Carbon::create(2024, 4, 1, 20, 0, 0, 'EST')),
379379
],
380380
[
381-
'_id' => 'MSG-0212252000',
381+
'id' => 'MSG-0212252000',
382382
'performer' => 'Brad Mehldau',
383383
'venue' => 'Philharmonie de Paris',
384384
'genres' => [ 'jazz', 'post-bop' ],
385385
'ticketsSold' => 5745,
386386
'performanceDate' => new UTCDateTime(Carbon::create(2025, 2, 12, 20, 0, 0, 'CET')),
387387
],
388388
[
389-
'_id' => 'MSG-021222000',
389+
'id' => 'MSG-021222000',
390390
'performer' => 'Billy Joel',
391391
'venue' => 'Madison Square Garden',
392392
'genres' => [ 'rock', 'soft rock', 'pop rock' ],
393393
'ticketsSold' => 12852,
394394
'performanceDate' => new UTCDateTime(Carbon::create(2025, 2, 12, 20, 0, 0, 'CET')),
395395
],
396396
[
397-
'_id' => 'SF-06302000',
397+
'id' => 'SF-06302000',
398398
'performer' => 'The Rolling Stones',
399399
'venue' => 'Soldier Field',
400400
'genres' => [ 'rock', 'pop', 'blues' ],
@@ -478,22 +478,22 @@ public function testModelDeleteMultipleById(): void
478478
Concert::truncate();
479479
$data = [
480480
[
481-
'_id' => 3,
481+
'id' => 3,
482482
'performer' => 'Mitsuko Uchida',
483483
'venue' => 'Carnegie Hall',
484484
],
485485
[
486-
'_id' => 5,
486+
'id' => 5,
487487
'performer' => 'Brad Mehldau',
488488
'venue' => 'Philharmonie de Paris',
489489
],
490490
[
491-
'_id' => 7,
491+
'id' => 7,
492492
'performer' => 'Billy Joel',
493493
'venue' => 'Madison Square Garden',
494494
],
495495
[
496-
'_id' => 9,
496+
'id' => 9,
497497
'performer' => 'The Rolling Stones',
498498
'venue' => 'Soldier Field',
499499
],

docs/includes/usage-examples/DeleteOneTest.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ public function testDeleteOne(): void
2727

2828
// begin-delete-one
2929
$deleted = Movie::where('title', 'Quiz Show')
30-
->orderBy('_id')
30+
->orderBy('id')
3131
->limit(1)
3232
->delete();
3333

docs/includes/usage-examples/FindManyTest.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ public function testFindMany(): void
3535

3636
// begin-find
3737
$movies = Movie::where('runtime', '>', 900)
38-
->orderBy('_id')
38+
->orderBy('id')
3939
->get();
4040
// end-find
4141

docs/includes/usage-examples/FindOneTest.php

+2-2
Original file line numberDiff line numberDiff line change
@@ -24,13 +24,13 @@ public function testFindOne(): void
2424

2525
// begin-find-one
2626
$movie = Movie::where('directors', 'Rob Reiner')
27-
->orderBy('_id')
27+
->orderBy('id')
2828
->first();
2929

3030
echo $movie->toJson();
3131
// end-find-one
3232

3333
$this->assertInstanceOf(Movie::class, $movie);
34-
$this->expectOutputRegex('/^{"_id":"[a-z0-9]{24}","title":"The Shawshank Redemption","directors":\["Frank Darabont","Rob Reiner"\]}$/');
34+
$this->expectOutputRegex('/^{"_id":"[a-z0-9]{24}","title":"The Shawshank Redemption","directors":\["Frank Darabont","Rob Reiner"\],"id":"[a-z0-9]{24}"}$/');
3535
}
3636
}

docs/includes/usage-examples/InsertOneTest.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,6 @@ public function testInsertOne(): void
3030
// end-insert-one
3131

3232
$this->assertInstanceOf(Movie::class, $movie);
33-
$this->expectOutputRegex('/^{"title":"Marriage Story","year":2019,"runtime":136,"updated_at":".{27}","created_at":".{27}","_id":"[a-z0-9]{24}"}$/');
33+
$this->expectOutputRegex('/^{"title":"Marriage Story","year":2019,"runtime":136,"updated_at":".{27}","created_at":".{27}","id":"[a-z0-9]{24}"}$/');
3434
}
3535
}

docs/includes/usage-examples/UpdateOneTest.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ public function testUpdateOne(): void
3030

3131
// begin-update-one
3232
$updates = Movie::where('title', 'Carol')
33-
->orderBy('_id')
33+
->orderBy('id')
3434
->first()
3535
->update([
3636
'imdb' => [

src/Auth/User.php

-1
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,5 @@ class User extends BaseUser
1111
{
1212
use DocumentModel;
1313

14-
protected $primaryKey = '_id';
1514
protected $keyType = 'string';
1615
}

src/Eloquent/DocumentModel.php

+9-8
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@
4646
use function str_contains;
4747
use function str_starts_with;
4848
use function strcmp;
49+
use function strlen;
4950
use function trigger_error;
5051
use function var_export;
5152

@@ -79,9 +80,7 @@ public function getIdAttribute($value = null)
7980
{
8081
// If we don't have a value for 'id', we will use the MongoDB '_id' value.
8182
// This allows us to work with models in a more sql-like way.
82-
if (! $value && array_key_exists('_id', $this->attributes)) {
83-
$value = $this->attributes['_id'];
84-
}
83+
$value ??= $this->attributes['id'] ?? $this->attributes['_id'] ?? null;
8584

8685
// Convert ObjectID to string.
8786
if ($value instanceof ObjectID) {
@@ -248,10 +247,8 @@ public function setAttribute($key, $value)
248247
}
249248

250249
// Convert _id to ObjectID.
251-
if ($key === '_id' && is_string($value)) {
252-
$builder = $this->newBaseQueryBuilder();
253-
254-
$value = $builder->convertKey($value);
250+
if (($key === '_id' || $key === 'id') && is_string($value) && strlen($value) === 24) {
251+
$value = $this->newBaseQueryBuilder()->convertKey($value);
255252
}
256253

257254
// Support keys in dot notation.
@@ -729,12 +726,16 @@ protected function isBSON(mixed $value): bool
729726
*/
730727
public function save(array $options = [])
731728
{
732-
// SQL databases would use autoincrement the id field if set to null.
729+
// SQL databases would autoincrement the id field if set to null.
733730
// Apply the same behavior to MongoDB with _id only, otherwise null would be stored.
734731
if (array_key_exists('_id', $this->attributes) && $this->attributes['_id'] === null) {
735732
unset($this->attributes['_id']);
736733
}
737734

735+
if (array_key_exists('id', $this->attributes) && $this->attributes['id'] === null) {
736+
unset($this->attributes['id']);
737+
}
738+
738739
$saved = parent::save($options);
739740

740741
// Clear list of unset fields

src/Eloquent/Model.php

-7
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,6 @@ abstract class Model extends BaseModel
1616
{
1717
use DocumentModel;
1818

19-
/**
20-
* The primary key for the model.
21-
*
22-
* @var string
23-
*/
24-
protected $primaryKey = '_id';
25-
2619
/**
2720
* The primary key type.
2821
*

src/Query/Builder.php

+5-1
Original file line numberDiff line numberDiff line change
@@ -516,7 +516,9 @@ public function getFresh($columns = [], $returnLazy = false)
516516
}
517517

518518
foreach ($result as &$document) {
519-
$document = $this->aliasIdForResult($document);
519+
if (is_array($document)) {
520+
$document = $this->aliasIdForResult($document);
521+
}
520522
}
521523

522524
return new Collection($result);
@@ -710,6 +712,8 @@ public function insertGetId(array $values, $sequence = null)
710712
{
711713
$options = $this->inheritConnectionOptions();
712714

715+
$values = $this->aliasIdForQuery($values);
716+
713717
$result = $this->collection->insertOne($values, $options);
714718

715719
if (! $result->isAcknowledged()) {

src/Relations/EmbedsMany.php

+5-5
Original file line numberDiff line numberDiff line change
@@ -46,9 +46,9 @@ public function getResults()
4646
*/
4747
public function performInsert(Model $model)
4848
{
49-
// Generate a new key if needed.
50-
if ($model->getKeyName() === '_id' && ! $model->getKey()) {
51-
$model->setAttribute('_id', new ObjectID());
49+
// Create a new key if needed.
50+
if (($model->getKeyName() === '_id' || $model->getKeyName() === 'id') && ! $model->getKey()) {
51+
$model->setAttribute($model->getKeyName(), new ObjectID());
5252
}
5353

5454
// For deeply nested documents, let the parent handle the changes.
@@ -249,8 +249,8 @@ public function attach(Model $model)
249249
protected function associateNew($model)
250250
{
251251
// Create a new key if needed.
252-
if ($model->getKeyName() === '_id' && ! $model->getAttribute('_id')) {
253-
$model->setAttribute('_id', new ObjectID());
252+
if (($model->getKeyName() === '_id' || $model->getKeyName() === 'id') && ! $model->getKey()) {
253+
$model->setAttribute($model->getKeyName(), new ObjectID());
254254
}
255255

256256
$records = $this->getEmbedded();

src/Relations/EmbedsOne.php

+3-3
Original file line numberDiff line numberDiff line change
@@ -42,9 +42,9 @@ public function getEager()
4242
*/
4343
public function performInsert(Model $model)
4444
{
45-
// Generate a new key if needed.
46-
if ($model->getKeyName() === '_id' && ! $model->getKey()) {
47-
$model->setAttribute('_id', new ObjectID());
45+
// Create a new key if needed.
46+
if (($model->getKeyName() === '_id' || $model->getKeyName() === 'id') && ! $model->getKey()) {
47+
$model->setAttribute($model->getKeyName(), new ObjectID());
4848
}
4949

5050
// For deeply nested documents, let the parent handle the changes.

tests/AuthTest.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ public function testRemindOld()
5252
$broker->sendResetLink(
5353
['email' => '[email protected]'],
5454
function ($actualUser, $actualToken) use ($user, &$token) {
55-
$this->assertEquals($user->_id, $actualUser->_id);
55+
$this->assertEquals($user->id, $actualUser->id);
5656
// Store token for later use
5757
$token = $actualToken;
5858
},

0 commit comments

Comments
 (0)