- 6. The Advanced Stuff
6.2. Primary Keys - 6.1. Indexing
« Previous - 6.3. Named Scopes
Next »
6.2. Primary Keys
Author | Dariusz Górecki |
---|
By default YiiMongoDbSuite will always use the _id
field as a collection primary key.
MongoDB itself guarantee that
_id
field will be unique across collection.
The _id
field
The _id
field in a short is, be default an instance of MongoID
class.
If you will do echo $model->_id
you will see something like: '4ced75e1eb4ae8ca44000000'
This is basically, the textual representation of auto-generated by MongoDB _id field.
But be aware that MongoID is not a string!
This will not find anything! $model->findByPk('4ced75e1eb4ae8ca44000000');
To find an model with specified ID use:
$model->findByPk(new MongoID('4ced75e1eb4ae8ca44000000'));
You can put any value into an
_id
fieldMongoDB will auto populate _id field by MongoID objects only when it is set to
NULL
Own defined Primary Key for collection
You can define a own field to be used as a Primary Key for yours collection, see example:
class Client extends EMongoDocument { // ... // Define primaryKey method: public function primaryKey() { return 'personal_number'; // Model field name, by default the _id field is used } // Now you can: // Client::model()->findByPk(1234); // personal_number == 1234 // ... }
- 6.2. Primary Keys
6. The Advanced Stuff - « Previous
6.1. Indexing - Next »
6.3. Named Scopes