forked from mongodb/laravel-mongodb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheloquent-models.txt
522 lines (350 loc) · 11.9 KB
/
eloquent-models.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
.. _laravel-eloquent-models:
===============
Eloquent Models
===============
.. facet::
:name: genre
:values: tutorial
.. meta::
:keywords: php framework, odm, code example
This package includes a MongoDB enabled Eloquent class that you can use to
define models for corresponding collections.
Extending the base model
~~~~~~~~~~~~~~~~~~~~~~~~
To get started, create a new model class in your ``app\Models\`` directory.
.. code-block:: php
namespace App\Models;
use MongoDB\Laravel\Eloquent\Model;
class Book extends Model
{
//
}
Just like a regular model, the MongoDB model class will know which collection
to use based on the model name. For ``Book``, the collection ``books`` will
be used.
To change the collection, pass the ``$collection`` property:
.. code-block:: php
use MongoDB\Laravel\Eloquent\Model;
class Book extends Model
{
protected $collection = 'my_books_collection';
}
.. note::
MongoDB documents are automatically stored with a unique ID that is stored
in the ``_id`` property. If you wish to use your own ID, substitute the
``$primaryKey`` property and set it to your own primary key attribute name.
.. code-block:: php
use MongoDB\Laravel\Eloquent\Model;
class Book extends Model
{
protected $primaryKey = 'id';
}
// MongoDB will also create _id, but the 'id' property will be used for primary key actions like find().
Book::create(['id' => 1, 'title' => 'The Fault in Our Stars']);
Likewise, you may define a ``connection`` property to override the name of the
database connection to reference the model.
.. code-block:: php
use MongoDB\Laravel\Eloquent\Model;
class Book extends Model
{
protected $connection = 'mongodb';
}
Soft Deletes
~~~~~~~~~~~~
When soft deleting a model, it is not actually removed from your database.
Instead, a ``deleted_at`` timestamp is set on the record.
To enable soft delete for a model, apply the ``MongoDB\Laravel\Eloquent\SoftDeletes``
Trait to the model:
.. code-block:: php
use MongoDB\Laravel\Eloquent\SoftDeletes;
class User extends Model
{
use SoftDeletes;
}
For more information check `Laravel Docs about Soft Deleting <http://laravel.com/docs/eloquent#soft-deleting>`__.
Prunable
~~~~~~~~
``Prunable`` and ``MassPrunable`` traits are Laravel features to automatically
remove models from your database. You can use ``Illuminate\Database\Eloquent\Prunable``
trait to remove models one by one. If you want to remove models in bulk, you
must use the ``MongoDB\Laravel\Eloquent\MassPrunable`` trait instead: it
will be more performant but can break links with other documents as it does
not load the models.
.. code-block:: php
use MongoDB\Laravel\Eloquent\Model;
use MongoDB\Laravel\Eloquent\MassPrunable;
class Book extends Model
{
use MassPrunable;
}
For more information check `Laravel Docs about Pruning Models <http://laravel.com/docs/eloquent#pruning-models>`__.
Dates
~~~~~
Eloquent allows you to work with Carbon or DateTime objects instead of MongoDate objects. Internally, these dates will be converted to MongoDate objects when saved to the database.
.. code-block:: php
use MongoDB\Laravel\Eloquent\Model;
class User extends Model
{
protected $casts = ['birthday' => 'datetime'];
}
This allows you to execute queries like this:
.. code-block:: php
$users = User::where(
'birthday', '>',
new DateTime('-18 years')
)->get();
Extending the Authenticatable base model
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This package includes a MongoDB Authenticatable Eloquent class ``MongoDB\Laravel\Auth\User``
that you can use to replace the default Authenticatable class ``Illuminate\Foundation\Auth\User``
for your ``User`` model.
.. code-block:: php
use MongoDB\Laravel\Auth\User as Authenticatable;
class User extends Authenticatable
{
}
Guarding attributes
~~~~~~~~~~~~~~~~~~~
When choosing between guarding attributes or marking some as fillable, Taylor
Otwell prefers the fillable route. This is in light of
`recent security issues described here <https://blog.laravel.com/security-release-laravel-61835-7240>`__.
Keep in mind guarding still works, but you may experience unexpected behavior.
Schema
------
The database driver also has (limited) schema builder support. You can
conveniently manipulate collections and set indexes.
Basic Usage
~~~~~~~~~~~
.. code-block:: php
Schema::create('users', function ($collection) {
$collection->index('name');
$collection->unique('email');
});
You can also pass all the parameters specified :manual:`in the MongoDB docs </reference/method/db.collection.createIndex/#options-for-all-index-types>`
to the ``$options`` parameter:
.. code-block:: php
Schema::create('users', function ($collection) {
$collection->index(
'username',
null,
null,
[
'sparse' => true,
'unique' => true,
'background' => true,
]
);
});
Inherited operations:
* create and drop
* collection
* hasCollection
* index and dropIndex (compound indexes supported as well)
* unique
MongoDB specific operations:
* background
* sparse
* expire
* geospatial
All other (unsupported) operations are implemented as dummy pass-through
methods because MongoDB does not use a predefined schema.
Read more about the schema builder on `Laravel Docs <https://laravel.com/docs/10.x/migrations#tables>`__
Geospatial indexes
~~~~~~~~~~~~~~~~~~
Geospatial indexes can improve query performance of location-based documents.
They come in two forms: ``2d`` and ``2dsphere``. Use the schema builder to add
these to a collection.
.. code-block:: php
Schema::create('bars', function ($collection) {
$collection->geospatial('location', '2d');
});
To add a ``2dsphere`` index:
.. code-block:: php
Schema::create('bars', function ($collection) {
$collection->geospatial('location', '2dsphere');
});
Relationships
-------------
Basic Usage
~~~~~~~~~~~
The only available relationships are:
* hasOne
* hasMany
* belongsTo
* belongsToMany
The MongoDB-specific relationships are:
* embedsOne
* embedsMany
Here is a small example:
.. code-block:: php
use MongoDB\Laravel\Eloquent\Model;
class User extends Model
{
public function items()
{
return $this->hasMany(Item::class);
}
}
The inverse relation of ``hasMany`` is ``belongsTo``:
.. code-block:: php
use MongoDB\Laravel\Eloquent\Model;
class Item extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
belongsToMany and pivots
~~~~~~~~~~~~~~~~~~~~~~~~
The belongsToMany relation will not use a pivot "table" but will push id's to
a **related_ids** attribute instead. This makes the second parameter for the
belongsToMany method useless.
If you want to define custom keys for your relation, set it to ``null``:
.. code-block:: php
use MongoDB\Laravel\Eloquent\Model;
class User extends Model
{
public function groups()
{
return $this->belongsToMany(
Group::class, null, 'user_ids', 'group_ids'
);
}
}
EmbedsMany Relationship
~~~~~~~~~~~~~~~~~~~~~~~
If you want to embed models, rather than referencing them, you can use the
``embedsMany`` relation. This relation is similar to the ``hasMany`` relation
but embeds the models inside the parent object.
**REMEMBER**\ : These relations return Eloquent collections, they don't return
query builder objects!
.. code-block:: php
use MongoDB\Laravel\Eloquent\Model;
class User extends Model
{
public function books()
{
return $this->embedsMany(Book::class);
}
}
You can access the embedded models through the dynamic property:
.. code-block:: php
$user = User::first();
foreach ($user->books as $book) {
//
}
The inverse relation is auto *magically* available. You can omit the reverse
relation definition.
.. code-block:: php
$book = Book::first();
$user = $book->user;
Inserting and updating embedded models works similar to the ``hasMany`` relation:
.. code-block:: php
$book = $user->books()->save(
new Book(['title' => 'A Game of Thrones'])
);
// or
$book =
$user->books()
->create(['title' => 'A Game of Thrones']);
You can update embedded models using their ``save`` method (available since
release 2.0.0):
.. code-block:: php
$book = $user->books()->first();
$book->title = 'A Game of Thrones';
$book->save();
You can remove an embedded model by using the ``destroy`` method on the
relation, or the ``delete`` method on the model (available since release 2.0.0):
.. code-block:: php
$book->delete();
// Similar operation
$user->books()->destroy($book);
If you want to add or remove an embedded model, without touching the database,
you can use the ``associate`` and ``dissociate`` methods.
To eventually write the changes to the database, save the parent object:
.. code-block:: php
$user->books()->associate($book);
$user->save();
Like other relations, embedsMany assumes the local key of the relationship
based on the model name. You can override the default local key by passing a
second argument to the embedsMany method:
.. code-block:: php
use MongoDB\Laravel\Eloquent\Model;
class User extends Model
{
public function books()
{
return $this->embedsMany(Book::class, 'local_key');
}
}
Embedded relations will return a Collection of embedded items instead of a
query builder. Check out the available operations here:
`https://laravel.com/docs/master/collections <https://laravel.com/docs/master/collections>`__
EmbedsOne Relationship
~~~~~~~~~~~~~~~~~~~~~~
The embedsOne relation is similar to the embedsMany relation, but only embeds a single model.
.. code-block:: php
use MongoDB\Laravel\Eloquent\Model;
class Book extends Model
{
public function author()
{
return $this->embedsOne(Author::class);
}
}
You can access the embedded models through the dynamic property:
.. code-block:: php
$book = Book::first();
$author = $book->author;
Inserting and updating embedded models works similar to the ``hasOne`` relation:
.. code-block:: php
$author = $book->author()->save(
new Author(['name' => 'John Doe'])
);
// Similar
$author =
$book->author()
->create(['name' => 'John Doe']);
You can update the embedded model using the ``save`` method (available since
release 2.0.0):
.. code-block:: php
$author = $book->author;
$author->name = 'Jane Doe';
$author->save();
You can replace the embedded model with a new model like this:
.. code-block:: php
$newAuthor = new Author(['name' => 'Jane Doe']);
$book->author()->save($newAuthor);
Cross-Database Relationships
----------------------------
If you're using a hybrid MongoDB and SQL setup, you can define relationships
across them.
The model will automatically return a MongoDB-related or SQL-related relation
based on the type of the related model.
If you want this functionality to work both ways, your SQL-models will need
to use the ``MongoDB\Laravel\Eloquent\HybridRelations`` trait.
**This functionality only works for ``hasOne``, ``hasMany`` and ``belongsTo``.**
The SQL model must use the ``HybridRelations`` trait:
.. code-block:: php
use MongoDB\Laravel\Eloquent\HybridRelations;
class User extends Model
{
use HybridRelations;
protected $connection = 'mysql';
public function messages()
{
return $this->hasMany(Message::class);
}
}
Within your MongoDB model, you must define the following relationship:
.. code-block:: php
use MongoDB\Laravel\Eloquent\Model;
class Message extends Model
{
protected $connection = 'mongodb';
public function user()
{
return $this->belongsTo(User::class);
}
}