Skip to content

PHPORM-147 Make id an alias for _id #3040

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Aug 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
# Changelog
All notable changes to this project will be documented in this file.

## [5.0.0] - next

* **BREAKING CHANGE** Use `id` as an alias for `_id` in commands and queries for compatibility with Eloquent packages by @GromNaN in [#3040](https://github.com/mongodb/laravel-mongodb/pull/3040)

## [4.8.0] - next

* Add `Query\Builder::incrementEach()` and `decrementEach()` methods by @SmallRuralDog in [#2550](https://github.com/mongodb/laravel-mongodb/pull/2550)
Expand Down
1 change: 0 additions & 1 deletion docs/includes/auth/PersonalAccessToken.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,5 @@ class PersonalAccessToken extends SanctumToken

protected $connection = 'mongodb';
protected $table = 'personal_access_tokens';
protected $primaryKey = '_id';
protected $keyType = 'string';
}
1 change: 0 additions & 1 deletion docs/includes/eloquent-models/PlanetThirdParty.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,5 @@ class Planet extends CelestialBody
use DocumentModel;

protected $fillable = ['name', 'diameter'];
protected $primaryKey = '_id';
protected $keyType = 'string';
}
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ public function testModelUpdateFluent(): void

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

$data = [
[
'_id' => 'CH-0401242000',
'id' => 'CH-0401242000',
'performer' => 'Mitsuko Uchida',
'venue' => 'Carnegie Hall',
'genres' => ['classical'],
'ticketsSold' => 2121,
'performanceDate' => new UTCDateTime(Carbon::create(2024, 4, 1, 20, 0, 0, 'EST')),
],
[
'_id' => 'MSG-0212252000',
'id' => 'MSG-0212252000',
'performer' => 'Brad Mehldau',
'venue' => 'Philharmonie de Paris',
'genres' => [ 'jazz', 'post-bop' ],
'ticketsSold' => 5745,
'performanceDate' => new UTCDateTime(Carbon::create(2025, 2, 12, 20, 0, 0, 'CET')),
],
[
'_id' => 'MSG-021222000',
'id' => 'MSG-021222000',
'performer' => 'Billy Joel',
'venue' => 'Madison Square Garden',
'genres' => [ 'rock', 'soft rock', 'pop rock' ],
'ticketsSold' => 12852,
'performanceDate' => new UTCDateTime(Carbon::create(2025, 2, 12, 20, 0, 0, 'CET')),
],
[
'_id' => 'SF-06302000',
'id' => 'SF-06302000',
'performer' => 'The Rolling Stones',
'venue' => 'Soldier Field',
'genres' => [ 'rock', 'pop', 'blues' ],
Expand Down Expand Up @@ -478,22 +478,22 @@ public function testModelDeleteMultipleById(): void
Concert::truncate();
$data = [
[
'_id' => 3,
'id' => 3,
'performer' => 'Mitsuko Uchida',
'venue' => 'Carnegie Hall',
],
[
'_id' => 5,
'id' => 5,
'performer' => 'Brad Mehldau',
'venue' => 'Philharmonie de Paris',
],
[
'_id' => 7,
'id' => 7,
'performer' => 'Billy Joel',
'venue' => 'Madison Square Garden',
],
[
'_id' => 9,
'id' => 9,
'performer' => 'The Rolling Stones',
'venue' => 'Soldier Field',
],
Expand Down
2 changes: 1 addition & 1 deletion docs/includes/usage-examples/DeleteOneTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public function testDeleteOne(): void

// begin-delete-one
$deleted = Movie::where('title', 'Quiz Show')
->orderBy('_id')
->orderBy('id')
->limit(1)
->delete();

Expand Down
2 changes: 1 addition & 1 deletion docs/includes/usage-examples/FindManyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public function testFindMany(): void

// begin-find
$movies = Movie::where('runtime', '>', 900)
->orderBy('_id')
->orderBy('id')
->get();
// end-find

Expand Down
4 changes: 2 additions & 2 deletions docs/includes/usage-examples/FindOneTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,13 @@ public function testFindOne(): void

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

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

$this->assertInstanceOf(Movie::class, $movie);
$this->expectOutputRegex('/^{"_id":"[a-z0-9]{24}","title":"The Shawshank Redemption","directors":\["Frank Darabont","Rob Reiner"\]}$/');
$this->expectOutputRegex('/^{"_id":"[a-z0-9]{24}","title":"The Shawshank Redemption","directors":\["Frank Darabont","Rob Reiner"\],"id":"[a-z0-9]{24}"}$/');
}
}
2 changes: 1 addition & 1 deletion docs/includes/usage-examples/InsertOneTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,6 @@ public function testInsertOne(): void
// end-insert-one

$this->assertInstanceOf(Movie::class, $movie);
$this->expectOutputRegex('/^{"title":"Marriage Story","year":2019,"runtime":136,"updated_at":".{27}","created_at":".{27}","_id":"[a-z0-9]{24}"}$/');
$this->expectOutputRegex('/^{"title":"Marriage Story","year":2019,"runtime":136,"updated_at":".{27}","created_at":".{27}","id":"[a-z0-9]{24}"}$/');
}
}
2 changes: 1 addition & 1 deletion docs/includes/usage-examples/UpdateOneTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public function testUpdateOne(): void

// begin-update-one
$updates = Movie::where('title', 'Carol')
->orderBy('_id')
->orderBy('id')
->first()
->update([
'imdb' => [
Expand Down
1 change: 0 additions & 1 deletion src/Auth/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,5 @@ class User extends BaseUser
{
use DocumentModel;

protected $primaryKey = '_id';
protected $keyType = 'string';
}
17 changes: 9 additions & 8 deletions src/Eloquent/DocumentModel.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
use function str_contains;
use function str_starts_with;
use function strcmp;
use function strlen;
use function trigger_error;
use function var_export;

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

// Convert ObjectID to string.
if ($value instanceof ObjectID) {
Expand Down Expand Up @@ -248,10 +247,8 @@ public function setAttribute($key, $value)
}

// Convert _id to ObjectID.
if ($key === '_id' && is_string($value)) {
$builder = $this->newBaseQueryBuilder();

$value = $builder->convertKey($value);
if (($key === '_id' || $key === 'id') && is_string($value) && strlen($value) === 24) {
$value = $this->newBaseQueryBuilder()->convertKey($value);
}

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

if (array_key_exists('id', $this->attributes) && $this->attributes['id'] === null) {
unset($this->attributes['id']);
}

$saved = parent::save($options);

// Clear list of unset fields
Expand Down
7 changes: 0 additions & 7 deletions src/Eloquent/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,6 @@ abstract class Model extends BaseModel
{
use DocumentModel;

/**
* The primary key for the model.
*
* @var string
*/
protected $primaryKey = '_id';

/**
* The primary key type.
*
Expand Down
Loading
Loading