Skip to content

Commit f6da16b

Browse files
authored
Merge pull request #5335 from kenjis/fix-docs-/model.rst
docs: impove model.rst
2 parents 0406780 + ab03da9 commit f6da16b

File tree

1 file changed

+55
-54
lines changed

1 file changed

+55
-54
lines changed

user_guide_src/source/models/model.rst

Lines changed: 55 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ Using CodeIgniter's Model
99
Models
1010
======
1111

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
1313
methods for much of the standard ways you would need to interact with a database table, including finding records,
1414
updating records, deleting records, and more.
1515

@@ -100,7 +100,7 @@ Connecting to the Database
100100

101101
When the class is first instantiated, if no database connection instance is passed to the constructor,
102102
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.
104104
This ensures that within the model any references to ``$this->db`` are made through the appropriate
105105
connection.
106106
::
@@ -175,60 +175,60 @@ Specifies if the table uses an auto-increment feature for ``$primaryKey``. If se
175175
then you are responsible for providing primary key value for every record in the table. This
176176
feature may be handy when we want to implement 1:1 relation or use UUIDs for our model.
177177

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
179179
key in the database to ``unique``. This way you will make sure that all of Model's features
180180
will still work the same as before.
181181

182182
**$returnType**
183183

184184
The Model's CRUD methods will take a step of work away from you and automatically return
185185
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()``
188188
method.
189189

190190
**$useSoftDeletes**
191191

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
193193
actually deleting the row. This can preserve data when it might be referenced elsewhere, or
194194
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.
197197

198198
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.
201201

202202
**$allowedFields**
203203

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
206206
against just taking input from a form and throwing it all at the model, resulting in
207207
potential mass assignment vulnerabilities.
208208

209209
**$useTimestamps**
210210

211211
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
214214
data type.
215215

216216
**$createdField**
217217

218218
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).
220220

221221
**$updatedField**
222222

223223
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).
225225

226226
**$dateFormat**
227227

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
229229
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.
232232

233233
**$validationRules**
234234

@@ -243,7 +243,7 @@ described in :ref:`validation-custom-errors`. Described in more detail below.
243243

244244
**$skipValidation**
245245

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
247247
value is false, meaning that data will always attempt to be validated. This is
248248
primarily used by the ``skipValidation()`` method, but may be changed to ``true`` so
249249
this model will never validate.
@@ -268,32 +268,32 @@ Working With Data
268268
Finding Data
269269
------------
270270

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.
273273

274274
**find()**
275275

276276
Returns a single row where the primary key matches the value passed in as the first parameter::
277277

278278
$user = $userModel->find($user_id);
279279

280-
The value is returned in the format specified in $returnType.
280+
The value is returned in the format specified in ``$returnType``.
281281

282282
You can specify more than one row to return by passing an array of primaryKey values instead
283283
of just one::
284284

285285
$users = $userModel->find([1,2,3]);
286286

287287
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.
289289

290290
**findColumn()**
291291

292292
Returns null or an indexed array of column values::
293293

294294
$user = $userModel->findColumn($column_name);
295295

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.
297297

298298
**findAll()**
299299

@@ -321,8 +321,8 @@ Returns the first row in the result set. This is best used in combination with t
321321

322322
**withDeleted()**
323323

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.
326326
::
327327

328328
// Only gets non-deleted rows (deleted = 0)
@@ -333,8 +333,8 @@ To temporarily override this, you can use the withDeleted() method prior to call
333333

334334
**onlyDeleted()**
335335

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::
338338

339339
$deletedUsers = $userModel->onlyDeleted()->findAll();
340340

@@ -344,7 +344,7 @@ Saving Data
344344
**insert()**
345345

346346
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
348348
the array's values are the values to save for that key::
349349

350350
$data = [
@@ -356,9 +356,9 @@ the array's values are the values to save for that key::
356356

357357
**update()**
358358

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.
360360
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::
362362

363363
$data = [
364364
'username' => 'darth',
@@ -385,8 +385,8 @@ update command, with the added benefit of validation, events, etc::
385385

386386
**save()**
387387

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::
390390

391391
// Defined as a model property
392392
$primaryKey = 'id';
@@ -476,7 +476,7 @@ Takes a primary key value as the first parameter and deletes the matching record
476476

477477
$userModel->delete(12);
478478

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
480480
date and time. You can force a permanent delete by setting the second parameter as true.
481481

482482
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,
591591
Now, whenever you call the ``insert()``, ``update()``, or ``save()`` methods, the data will be validated. If it fails,
592592
the model will return boolean **false**. You can use the ``errors()`` method to retrieve the validation errors::
593593

594-
if ($model->save($data) === false)
595-
{
594+
if ($model->save($data) === false) {
596595
return view('updateUser', ['errors' => $model->errors()]);
597596
}
598597

599598
This returns an array with the field names and their associated errors that can be used to either show all of the
600599
errors at the top of the form, or to display them individually::
601600

602-
<?php if (! empty($errors)) : ?>
601+
<?php if (! empty($errors)): ?>
603602
<div class="alert alert-danger">
604-
<?php foreach ($errors as $field => $error) : ?>
603+
<?php foreach ($errors as $field => $error): ?>
605604
<p><?= $error ?></p>
606605
<?php endforeach ?>
607606
</div>
@@ -629,7 +628,7 @@ method directly, with options::
629628
$rules = $model->getValidationRules($options);
630629

631630
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
633632
value an array of fieldnames of interest.::
634633

635634
// get the rules for all but the "username" field
@@ -642,7 +641,7 @@ Validation Placeholders
642641

643642
The model provides a simple method to replace parts of your rules based on data that's being passed into it. This
644643
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
646645
replaced by the **value** of the matched incoming field. An example should clarify this::
647646

648647
protected $validationRules = [
@@ -694,7 +693,7 @@ need it::
694693

695694
$builder = $userModel->builder();
696695

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
698697
you can pass it in as a parameter, but be aware that this will not return a shared instance::
699698

700699
$groupBuilder = $userModel->builder('groups');
@@ -713,22 +712,22 @@ very elegant use::
713712
Runtime Return Type Changes
714713
----------------------------
715714

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
718717
provides methods that allow you to do just that.
719718

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,
721720
it is reset to its default value.
722721

723722
**asArray()**
724723

725-
Returns data from the next find*() method as associative arrays::
724+
Returns data from the next **find*()** method as associative arrays::
726725

727726
$users = $userModel->asArray()->where('status', 'active')->findAll();
728727

729728
**asObject()**
730729

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::
732731

733732
// Return as standard objects
734733
$users = $userModel->asObject()->where('status', 'active')->findAll();
@@ -757,14 +756,14 @@ Model Events
757756

758757
There are several points within the model's execution that you can specify multiple callback methods to run.
759758
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``.
762761

763762
Defining Callbacks
764763
------------------
765764

766765
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
768767
will always contain a key named **data** that contains the primary data passed to the original method. In the case
769768
of the insert* or update* methods, that will be the key/value pairs that are being inserted into the database. The
770769
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
774773

775774
protected function hashPassword(array $data)
776775
{
777-
if (! isset($data['data']['password'])) return $data;
776+
if (! isset($data['data']['password'])) {
777+
return $data;
778+
}
778779

779780
$data['data']['password_hash'] = password_hash($data['data']['password'], PASSWORD_DEFAULT);
780781
unset($data['data']['password']);
@@ -785,14 +786,14 @@ must return the original $data array so other callbacks have the full informatio
785786
Specifying Callbacks To Run
786787
---------------------------
787788

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``,
789790
etc). Multiple callbacks can be added to a single event and they will be processed one after the other. You can
790791
use the same callback in multiple events::
791792

792793
protected $beforeInsert = ['hashPassword'];
793794
protected $beforeUpdate = ['hashPassword'];
794795

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::
796797

797798
protected $allowCallbacks = false;
798799

@@ -804,7 +805,7 @@ You may also change this setting temporarily for a single model call sing the ``
804805
Event Parameters
805806
----------------
806807

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
808809
passed to each event:
809810

810811
================ =========================================================================================================

0 commit comments

Comments
 (0)