@@ -9,7 +9,7 @@ Using CodeIgniter's Model
9
9
Models
10
10
======
11
11
12
- Models provide a way to interact with a specific table in your database. They come out of the box with helper
12
+ Models provide a way to interact with a specific ** table ** in your database. They come out of the box with helper
13
13
methods for much of the standard ways you would need to interact with a database table, including finding records,
14
14
updating records, deleting records, and more.
15
15
@@ -100,7 +100,7 @@ Connecting to the Database
100
100
101
101
When the class is first instantiated, if no database connection instance is passed to the constructor,
102
102
it will automatically connect to the default database group, as set in the configuration. You can
103
- modify which group is used on a per-model basis by adding the DBGroup property to your class.
103
+ modify which group is used on a per-model basis by adding the `` $ DBGroup`` property to your class.
104
104
This ensures that within the model any references to ``$this->db `` are made through the appropriate
105
105
connection.
106
106
::
@@ -175,60 +175,60 @@ Specifies if the table uses an auto-increment feature for ``$primaryKey``. If se
175
175
then you are responsible for providing primary key value for every record in the table. This
176
176
feature may be handy when we want to implement 1:1 relation or use UUIDs for our model.
177
177
178
- .. note :: If you set ``$useAutoIncrement`` to ``false`` then make sure to set your primary
178
+ .. note :: If you set ``$useAutoIncrement`` to ``false``, then make sure to set your primary
179
179
key in the database to ``unique ``. This way you will make sure that all of Model's features
180
180
will still work the same as before.
181
181
182
182
**$returnType **
183
183
184
184
The Model's CRUD methods will take a step of work away from you and automatically return
185
185
the resulting data, instead of the Result object. This setting allows you to define
186
- the type of data that is returned. Valid values are 'array' , 'object', or the fully
187
- qualified name of a class that can be used with the Result object's getCustomResultObject()
186
+ the type of data that is returned. Valid values are '** array **' (the default) , '** object ** ', or the ** fully
187
+ qualified name of a class ** that can be used with the Result object's `` getCustomResultObject() ``
188
188
method.
189
189
190
190
**$useSoftDeletes **
191
191
192
- If true, then any delete* method calls will set ``deleted_at `` in the database, instead of
192
+ If true, then any `` delete() `` method calls will set ``deleted_at `` in the database, instead of
193
193
actually deleting the row. This can preserve data when it might be referenced elsewhere, or
194
194
can maintain a "recycle bin" of objects that can be restored, or even simply preserve it as
195
- part of a security trail. If true, the find* methods will only return non-deleted rows, unless
196
- the withDeleted() method is called prior to calling the find* method.
195
+ part of a security trail. If true, the ** find*() * * methods will only return non-deleted rows, unless
196
+ the `` withDeleted() `` method is called prior to calling the ** find*() * * method.
197
197
198
198
This requires either a DATETIME or INTEGER field in the database as per the model's
199
- $dateFormat setting. The default field name is ``deleted_at `` however this name can be
200
- configured to any name of your choice by using $deletedField property.
199
+ `` $dateFormat `` setting. The default field name is ``deleted_at `` however this name can be
200
+ configured to any name of your choice by using `` $deletedField `` property.
201
201
202
202
**$allowedFields **
203
203
204
- This array should be updated with the field names that can be set during save, insert, or
205
- update methods. Any field names other than these will be discarded. This helps to protect
204
+ This array should be updated with the field names that can be set during `` save() ``, `` insert() `` , or
205
+ `` update() `` methods. Any field names other than these will be discarded. This helps to protect
206
206
against just taking input from a form and throwing it all at the model, resulting in
207
207
potential mass assignment vulnerabilities.
208
208
209
209
**$useTimestamps **
210
210
211
211
This boolean value determines whether the current date is automatically added to all inserts
212
- and updates. If true, will set the current time in the format specified by $dateFormat. This
213
- requires that the table have columns named ' created_at' and ' updated_at' in the appropriate
212
+ and updates. If true, will set the current time in the format specified by `` $dateFormat `` . This
213
+ requires that the table have columns named ** created_at ** and ** updated_at ** in the appropriate
214
214
data type.
215
215
216
216
**$createdField **
217
217
218
218
Specifies which database field to use for data record create timestamp.
219
- Leave it empty to avoid updating it (even if ``$useTimestamps `` is enabled)
219
+ Leave it empty to avoid updating it (even if ``$useTimestamps `` is enabled).
220
220
221
221
**$updatedField **
222
222
223
223
Specifies which database field should use for keep data record update timestamp.
224
- Leave it empty to avoid update it (even useTimestamps is enabled)
224
+ Leave it empty to avoid update it (even `` $ useTimestamps`` is enabled).
225
225
226
226
**$dateFormat **
227
227
228
- This value works with $useTimestamps and $useSoftDeletes to ensure that the correct type of
228
+ This value works with `` $useTimestamps `` and `` $useSoftDeletes `` to ensure that the correct type of
229
229
date value gets inserted into the database. By default, this creates DATETIME values, but
230
- valid options are: datetime, date, or int (a PHP timestamp). Using ' useSoftDeletes' or
231
- ' useTimestamps' with an invalid or missing dateFormat will cause an exception.
230
+ valid options are: `` ' datetime' ``, `` ' date' `` , or `` ' int' `` (a PHP timestamp). Using ** useSoftDeletes ** or
231
+ ** useTimestamps ** with an invalid or missing dateFormat will cause an exception.
232
232
233
233
**$validationRules **
234
234
@@ -243,7 +243,7 @@ described in :ref:`validation-custom-errors`. Described in more detail below.
243
243
244
244
**$skipValidation **
245
245
246
- Whether validation should be skipped during all `` inserts `` and `` updates `` . The default
246
+ Whether validation should be skipped during all ** inserts ** and ** updates ** . The default
247
247
value is false, meaning that data will always attempt to be validated. This is
248
248
primarily used by the ``skipValidation() `` method, but may be changed to ``true `` so
249
249
this model will never validate.
@@ -268,32 +268,32 @@ Working With Data
268
268
Finding Data
269
269
------------
270
270
271
- Several functions are provided for doing basic CRUD work on your tables, including find(),
272
- insert(), update(), delete() and more.
271
+ Several functions are provided for doing basic CRUD work on your tables, including `` find() `` ,
272
+ `` insert() ``, `` update() ``, `` delete() `` and more.
273
273
274
274
**find() **
275
275
276
276
Returns a single row where the primary key matches the value passed in as the first parameter::
277
277
278
278
$user = $userModel->find($user_id);
279
279
280
- The value is returned in the format specified in $returnType.
280
+ The value is returned in the format specified in `` $returnType `` .
281
281
282
282
You can specify more than one row to return by passing an array of primaryKey values instead
283
283
of just one::
284
284
285
285
$users = $userModel->find([1,2,3]);
286
286
287
287
If no parameters are passed in, will return all rows in that model's table, effectively acting
288
- like findAll(), though less explicit.
288
+ like `` findAll() `` , though less explicit.
289
289
290
290
**findColumn() **
291
291
292
292
Returns null or an indexed array of column values::
293
293
294
294
$user = $userModel->findColumn($column_name);
295
295
296
- $column_name should be a name of single column else you will get the DataException.
296
+ `` $column_name `` should be a name of single column else you will get the DataException.
297
297
298
298
**findAll() **
299
299
@@ -321,8 +321,8 @@ Returns the first row in the result set. This is best used in combination with t
321
321
322
322
**withDeleted() **
323
323
324
- If $useSoftDeletes is true, then the find* methods will not return any rows where 'deleted_at IS NOT null '.
325
- To temporarily override this, you can use the withDeleted() method prior to calling the find* method.
324
+ If `` $useSoftDeletes `` is true, then the ** find*() ** methods will not return any rows where 'deleted_at IS NOT NULL '.
325
+ To temporarily override this, you can use the `` withDeleted() `` method prior to calling the ** find*() * * method.
326
326
::
327
327
328
328
// Only gets non-deleted rows (deleted = 0)
@@ -333,8 +333,8 @@ To temporarily override this, you can use the withDeleted() method prior to call
333
333
334
334
**onlyDeleted() **
335
335
336
- Whereas withDeleted() will return both deleted and not-deleted rows, this method modifies
337
- the next find* methods to return only soft deleted rows::
336
+ Whereas `` withDeleted() `` will return both deleted and not-deleted rows, this method modifies
337
+ the next ** find*() * * methods to return only soft deleted rows::
338
338
339
339
$deletedUsers = $userModel->onlyDeleted()->findAll();
340
340
@@ -344,7 +344,7 @@ Saving Data
344
344
**insert() **
345
345
346
346
An associative array of data is passed into this method as the only parameter to create a new
347
- row of data in the database. The array's keys must match the name of the columns in a $table, while
347
+ row of data in the database. The array's keys must match the name of the columns in a `` $table `` , while
348
348
the array's values are the values to save for that key::
349
349
350
350
$data = [
@@ -356,9 +356,9 @@ the array's values are the values to save for that key::
356
356
357
357
**update() **
358
358
359
- Updates an existing record in the database. The first parameter is the $primaryKey of the record to update.
359
+ Updates an existing record in the database. The first parameter is the `` $primaryKey `` of the record to update.
360
360
An associative array of data is passed into this method as the second parameter. The array's keys must match the name
361
- of the columns in a $table, while the array's values are the values to save for that key::
361
+ of the columns in a `` $table `` , while the array's values are the values to save for that key::
362
362
363
363
$data = [
364
364
'username' => 'darth',
@@ -385,8 +385,8 @@ update command, with the added benefit of validation, events, etc::
385
385
386
386
**save() **
387
387
388
- This is a wrapper around the insert() and update() methods that handle inserting or updating the record
389
- automatically, based on whether it finds an array key matching the $primaryKey value::
388
+ This is a wrapper around the `` insert() `` and `` update() `` methods that handle inserting or updating the record
389
+ automatically, based on whether it finds an array key matching the ** primary key ** value::
390
390
391
391
// Defined as a model property
392
392
$primaryKey = 'id';
@@ -476,7 +476,7 @@ Takes a primary key value as the first parameter and deletes the matching record
476
476
477
477
$userModel->delete(12);
478
478
479
- If the model's $useSoftDeletes value is true, this will update the row to set ``deleted_at `` to the current
479
+ If the model's `` $useSoftDeletes `` value is true, this will update the row to set ``deleted_at `` to the current
480
480
date and time. You can force a permanent delete by setting the second parameter as true.
481
481
482
482
An array of primary keys can be passed in as the first parameter to delete multiple records at once::
@@ -591,17 +591,16 @@ The other way to set the validation message to fields by functions,
591
591
Now, whenever you call the ``insert() ``, ``update() ``, or ``save() `` methods, the data will be validated. If it fails,
592
592
the model will return boolean **false **. You can use the ``errors() `` method to retrieve the validation errors::
593
593
594
- if ($model->save($data) === false)
595
- {
594
+ if ($model->save($data) === false) {
596
595
return view('updateUser', ['errors' => $model->errors()]);
597
596
}
598
597
599
598
This returns an array with the field names and their associated errors that can be used to either show all of the
600
599
errors at the top of the form, or to display them individually::
601
600
602
- <?php if (! empty($errors)) : ?>
601
+ <?php if (! empty($errors)): ?>
603
602
<div class="alert alert-danger">
604
- <?php foreach ($errors as $field => $error) : ?>
603
+ <?php foreach ($errors as $field => $error): ?>
605
604
<p><?= $error ?></p>
606
605
<?php endforeach ?>
607
606
</div>
@@ -629,7 +628,7 @@ method directly, with options::
629
628
$rules = $model->getValidationRules($options);
630
629
631
630
The ``$options `` parameter is an associative array with one element,
632
- whose key is either " except" or " only" , and which has as its
631
+ whose key is either `` ' except' `` or `` ' only' `` , and which has as its
633
632
value an array of fieldnames of interest.::
634
633
635
634
// get the rules for all but the "username" field
@@ -642,7 +641,7 @@ Validation Placeholders
642
641
643
642
The model provides a simple method to replace parts of your rules based on data that's being passed into it. This
644
643
sounds fairly obscure but can be especially handy with the ``is_unique `` validation rule. Placeholders are simply
645
- the name of the field (or array key) that was passed in as $data surrounded by curly brackets. It will be
644
+ the name of the field (or array key) that was passed in as `` $data `` surrounded by curly brackets. It will be
646
645
replaced by the **value ** of the matched incoming field. An example should clarify this::
647
646
648
647
protected $validationRules = [
@@ -694,7 +693,7 @@ need it::
694
693
695
694
$builder = $userModel->builder();
696
695
697
- This builder is already set up with the model's $table. If you need access to another table
696
+ This builder is already set up with the model's `` $table `` . If you need access to another table
698
697
you can pass it in as a parameter, but be aware that this will not return a shared instance::
699
698
700
699
$groupBuilder = $userModel->builder('groups');
@@ -713,22 +712,22 @@ very elegant use::
713
712
Runtime Return Type Changes
714
713
----------------------------
715
714
716
- You can specify the format that data should be returned as when using the find*() methods as the class property,
717
- $returnType. There may be times that you would like the data back in a different format, though. The Model
715
+ You can specify the format that data should be returned as when using the ** find*() ** methods as the class property,
716
+ `` $returnType `` . There may be times that you would like the data back in a different format, though. The Model
718
717
provides methods that allow you to do just that.
719
718
720
- .. note :: These methods only change the return type for the next find*() method call. After that,
719
+ .. note :: These methods only change the return type for the next ** find*()** method call. After that,
721
720
it is reset to its default value.
722
721
723
722
**asArray() **
724
723
725
- Returns data from the next find*() method as associative arrays::
724
+ Returns data from the next ** find*() ** method as associative arrays::
726
725
727
726
$users = $userModel->asArray()->where('status', 'active')->findAll();
728
727
729
728
**asObject() **
730
729
731
- Returns data from the next find*() method as standard objects or custom class intances::
730
+ Returns data from the next ** find*() ** method as standard objects or custom class intances::
732
731
733
732
// Return as standard objects
734
733
$users = $userModel->asObject()->where('status', 'active')->findAll();
@@ -757,14 +756,14 @@ Model Events
757
756
758
757
There are several points within the model's execution that you can specify multiple callback methods to run.
759
758
These methods can be used to normalize data, hash passwords, save related entities, and much more. The following
760
- points in the model's execution can be affected, each through a class property: ** $beforeInsert **, ** $afterInsert ** ,
761
- ** $beforeUpdate **, ** $afterUpdate **, ** $afterFind ** , and ** $afterDelete ** .
759
+ points in the model's execution can be affected, each through a class property: `` $beforeInsert ``, `` $afterInsert `` ,
760
+ `` $beforeUpdate ``, `` $afterUpdate ``, `` $afterFind `` , and `` $afterDelete `` .
762
761
763
762
Defining Callbacks
764
763
------------------
765
764
766
765
You specify the callbacks by first creating a new class method in your model to use. This class will always
767
- receive a $data array as its only parameter. The exact contents of the $data array will vary between events, but
766
+ receive a `` $data `` array as its only parameter. The exact contents of the `` $data `` array will vary between events, but
768
767
will always contain a key named **data ** that contains the primary data passed to the original method. In the case
769
768
of the insert* or update* methods, that will be the key/value pairs that are being inserted into the database. The
770
769
main array will also contain the other values passed to the method, and be detailed later. The callback method
@@ -774,7 +773,9 @@ must return the original $data array so other callbacks have the full informatio
774
773
775
774
protected function hashPassword(array $data)
776
775
{
777
- if (! isset($data['data']['password'])) return $data;
776
+ if (! isset($data['data']['password'])) {
777
+ return $data;
778
+ }
778
779
779
780
$data['data']['password_hash'] = password_hash($data['data']['password'], PASSWORD_DEFAULT);
780
781
unset($data['data']['password']);
@@ -785,14 +786,14 @@ must return the original $data array so other callbacks have the full informatio
785
786
Specifying Callbacks To Run
786
787
---------------------------
787
788
788
- You specify when to run the callbacks by adding the method name to the appropriate class property (beforeInsert, afterUpdate,
789
+ You specify when to run the callbacks by adding the method name to the appropriate class property (`` $ beforeInsert``, `` $ afterUpdate`` ,
789
790
etc). Multiple callbacks can be added to a single event and they will be processed one after the other. You can
790
791
use the same callback in multiple events::
791
792
792
793
protected $beforeInsert = ['hashPassword'];
793
794
protected $beforeUpdate = ['hashPassword'];
794
795
795
- Additionally, each model may allow (default) or deny callbacks class-wide by setting its $allowCallbacks property::
796
+ Additionally, each model may allow (default) or deny callbacks class-wide by setting its `` $allowCallbacks `` property::
796
797
797
798
protected $allowCallbacks = false;
798
799
@@ -804,7 +805,7 @@ You may also change this setting temporarily for a single model call sing the ``
804
805
Event Parameters
805
806
----------------
806
807
807
- Since the exact data passed to each callback varies a bit, here are the details on what is in the $data parameter
808
+ Since the exact data passed to each callback varies a bit, here are the details on what is in the `` $data `` parameter
808
809
passed to each event:
809
810
810
811
================ =========================================================================================================
0 commit comments