Skip to content

Commit 6b06020

Browse files
authored
Merge pull request #6962 from kenjis/fix-docs-model.rst
docs: improve model.rst
2 parents d6b8bb1 + a2132f0 commit 6b06020

5 files changed

Lines changed: 130 additions & 70 deletions

File tree

user_guide_src/source/models/model.rst

Lines changed: 106 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,10 @@ that extends ``CodeIgniter\Model``:
5353
This empty class provides convenient access to the database connection, the Query Builder,
5454
and a number of additional convenience methods.
5555

56-
Should you need additional setup in your model you may extend the ``initialize()`` function
56+
initialize()
57+
============
58+
59+
Should you need additional setup in your model you may extend the ``initialize()`` method
5760
which will be run immediately after the Model's constructor. This allows you to perform
5861
extra steps without repeating the constructor parameters, for example extending other models:
5962

@@ -76,7 +79,7 @@ configuration file.
7679
Configuring Your Model
7780
======================
7881

79-
The model class has a few configuration options that can be set to allow the class' methods
82+
The model class has some configuration options that can be set to allow the class' methods
8083
to work seamlessly for you. The first two are used by all of the CRUD methods to determine
8184
what table to use and how we can find the required records:
8285

@@ -121,6 +124,8 @@ qualified name of a class** that can be used with the Result object's ``getCusto
121124
method. Using the special ``::class`` constant of the class will allow most IDEs to
122125
auto-complete the name and allow functions like refactoring to better understand your code.
123126

127+
.. _model-use-soft-deletes:
128+
124129
$useSoftDeletes
125130
---------------
126131

@@ -146,49 +151,60 @@ potential mass assignment vulnerabilities.
146151

147152
.. note:: The ``$primaryKey`` field should never be an allowed field.
148153

154+
Dates
155+
-----
156+
149157
$useTimestamps
150-
--------------
158+
^^^^^^^^^^^^^^
151159

152160
This boolean value determines whether the current date is automatically added to all inserts
153161
and updates. If true, will set the current time in the format specified by ``$dateFormat``. This
154-
requires that the table have columns named **created_at** and **updated_at** in the appropriate
162+
requires that the table have columns named **created_at**, **updated_at** and **deleted_at** in the appropriate
155163
data type.
156164

165+
$dateFormat
166+
^^^^^^^^^^^
167+
168+
This value works with ``$useTimestamps`` and ``$useSoftDeletes`` to ensure that the correct type of
169+
date value gets inserted into the database. By default, this creates DATETIME values, but
170+
valid options are: ``'datetime'``, ``'date'``, or ``'int'`` (a PHP timestamp). Using **useSoftDeletes** or
171+
**useTimestamps** with an invalid or missing **dateFormat** will cause an exception.
172+
157173
$createdField
158-
-------------
174+
^^^^^^^^^^^^^
159175

160176
Specifies which database field to use for data record create timestamp.
161177
Leave it empty to avoid updating it (even if ``$useTimestamps`` is enabled).
162178

163179
$updatedField
164-
-------------
180+
^^^^^^^^^^^^^
165181

166182
Specifies which database field should use for keep data record update timestamp.
167183
Leave it empty to avoid update it (even ``$useTimestamps`` is enabled).
168184

169-
$dateFormat
170-
-----------
185+
$deletedField
186+
^^^^^^^^^^^^^
171187

172-
This value works with ``$useTimestamps`` and ``$useSoftDeletes`` to ensure that the correct type of
173-
date value gets inserted into the database. By default, this creates DATETIME values, but
174-
valid options are: ``'datetime'``, ``'date'``, or ``'int'`` (a PHP timestamp). Using **useSoftDeletes** or
175-
useTimestamps with an invalid or missing dateFormat will cause an exception.
188+
Specifies which database field to use for soft deletions. See :ref:`model-use-soft-deletes`.
189+
190+
Validation
191+
----------
176192

177193
$validationRules
178-
----------------
194+
^^^^^^^^^^^^^^^^
179195

180196
Contains either an array of validation rules as described in :ref:`validation-array`
181197
or a string containing the name of a validation group, as described in the same section.
182198
Described in more detail below.
183199

184200
$validationMessages
185-
-------------------
201+
^^^^^^^^^^^^^^^^^^^
186202

187203
Contains an array of custom error messages that should be used during validation, as
188204
described in :ref:`validation-custom-errors`. Described in more detail below.
189205

190206
$skipValidation
191-
---------------
207+
^^^^^^^^^^^^^^^
192208

193209
Whether validation should be skipped during all **inserts** and **updates**. The default
194210
value is ``false``, meaning that data will always attempt to be validated. This is
@@ -198,7 +214,7 @@ this model will never validate.
198214
.. _clean-validation-rules:
199215

200216
$cleanValidationRules
201-
---------------------
217+
^^^^^^^^^^^^^^^^^^^^^
202218

203219
Whether validation rules should be removed that do not exist in the passed data.
204220
This is used in **updates**.
@@ -210,28 +226,35 @@ You can also change the value by the ``cleanRules()`` method.
210226

211227
.. note:: Prior to v4.2.7, ``$cleanValidationRules`` did not work due to a bug.
212228

229+
Callbacks
230+
---------
231+
232+
$allowCallbacks
233+
^^^^^^^^^^^^^^^
234+
235+
Whether the callbacks defined below should be used.
236+
213237
$beforeInsert
214-
-------------
238+
^^^^^^^^^^^^^
215239
$afterInsert
216-
------------
240+
^^^^^^^^^^^^
217241
$beforeUpdate
218-
-------------
242+
^^^^^^^^^^^^^
219243
$afterUpdate
220-
------------
244+
^^^^^^^^^^^^
245+
$beforeFind
246+
^^^^^^^^^^^
221247
$afterFind
222-
----------
248+
^^^^^^^^^^
249+
$beforeDelete
250+
^^^^^^^^^^^^^
223251
$afterDelete
224-
------------
252+
^^^^^^^^^^^^
225253

226254
These arrays allow you to specify callback methods that will be run on the data at the
227255
time specified in the property name.
228256

229-
$allowCallbacks
230-
---------------
231-
232-
Whether the callbacks defined above should be used.
233-
234-
Working With Data
257+
Working with Data
235258
*****************
236259

237260
Finding Data
@@ -254,8 +277,8 @@ of just one:
254277

255278
.. literalinclude:: model/007.php
256279

257-
If no parameters are passed in, will return all rows in that model's table, effectively acting
258-
like ``findAll()``, though less explicit.
280+
.. note:: If no parameters are passed in, ``find()`` will return all rows in that model's table,
281+
effectively acting like ``findAll()``, though less explicit.
259282

260283
findColumn()
261284
------------
@@ -264,7 +287,7 @@ Returns null or an indexed array of column values:
264287

265288
.. literalinclude:: model/008.php
266289

267-
``$column_name`` should be a name of single column else you will get the DataException.
290+
``$column_name`` should be a name of single column else you will get the ``DataException``.
268291

269292
findAll()
270293
---------
@@ -292,7 +315,7 @@ Returns the first row in the result set. This is best used in combination with t
292315
withDeleted()
293316
-------------
294317

295-
If ``$useSoftDeletes`` is true, then the **find*()** methods will not return any rows where 'deleted_at IS NOT NULL'.
318+
If ``$useSoftDeletes`` is true, then the **find*()** methods will not return any rows where ``deleted_at IS NOT NULL``.
296319
To temporarily override this, you can use the ``withDeleted()`` method prior to calling the **find*()** method.
297320

298321
.. literalinclude:: model/013.php
@@ -548,33 +571,6 @@ testing, migrations, or seeds. In these cases, you can turn the protection on or
548571

549572
.. literalinclude:: model/042.php
550573

551-
Working With Query Builder
552-
==========================
553-
554-
You can get access to a shared instance of the Query Builder for that model's database connection any time you
555-
need it:
556-
557-
.. literalinclude:: model/043.php
558-
559-
This builder is already set up with the model's ``$table``. If you need access to another table
560-
you can pass it in as a parameter, but be aware that this will not return a shared instance:
561-
562-
.. literalinclude:: model/044.php
563-
564-
You can also use Query Builder methods and the Model's CRUD methods in the same chained call, allowing for
565-
very elegant use:
566-
567-
.. literalinclude:: model/045.php
568-
569-
.. important:: The Model does not provide a perfect interface to the Query Builder.
570-
The Model and the Query Builder are separate classes with different purposes.
571-
They should not be expected to return the same data.
572-
For example, if you need to get the compiledInsert you should do so directly on the builder instance.
573-
574-
.. note:: You can also access the model's database connection seamlessly:
575-
576-
.. literalinclude:: model/046.php
577-
578574
Runtime Return Type Changes
579575
===========================
580576

@@ -611,6 +607,57 @@ This is best used during cronjobs, data exports, or other large tasks.
611607

612608
.. literalinclude:: model/049.php
613609

610+
Working with Query Builder
611+
**************************
612+
613+
Getting Query Builder for the Model's Table
614+
===========================================
615+
616+
CodeIgniter Model has one instance of the Query Builder for that model's database connection.
617+
You can get access to the **shared** instance of the Query Builder any time you need it:
618+
619+
.. literalinclude:: model/043.php
620+
621+
This builder is already set up with the model's ``$table``.
622+
623+
.. note:: Once you get the Query Builder instance, you can call methods of the
624+
:doc:`Query Builder <../database/query_builder>`.
625+
However, since Query Builder is not a Model, you cannot call methods of the Model.
626+
627+
Getting Query Builder for Another Table
628+
=======================================
629+
630+
If you need access to another table, you can get another instance of the Query Builder.
631+
Pass the table name in as a parameter, but be aware that this will **not** return
632+
a shared instance:
633+
634+
.. literalinclude:: model/044.php
635+
636+
Mixing Methods of Query Builder and Model
637+
=========================================
638+
639+
You can also use Query Builder methods and the Model's CRUD methods in the same chained call, allowing for
640+
very elegant use:
641+
642+
.. literalinclude:: model/045.php
643+
644+
In this case, it operates on the shared instance of the Query Builder held by the model.
645+
646+
.. important:: The Model does not provide a perfect interface to the Query Builder.
647+
The Model and the Query Builder are separate classes with different purposes.
648+
They should not be expected to return the same data.
649+
650+
If the Query Builder returns a result, it is returned as is.
651+
In that case, the result may be different from the one returned by the model's method
652+
and may not be what was expected. The model's events are not triggered.
653+
654+
To prevent unexpected behavior, do not use Query Builder methods that return results
655+
and specify the model's method at the end of the method chaining.
656+
657+
.. note:: You can also access the model's database connection seamlessly:
658+
659+
.. literalinclude:: model/046.php
660+
614661
Model Events
615662
************
616663

user_guide_src/source/models/model/001.php

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
11
<?php
22

3-
// Create a new class manually
3+
// Create a new class manually.
44
$userModel = new \App\Models\UserModel();
55

6-
// Create a new class with the model function
6+
// Create a new class with the model() function.
77
$userModel = model('App\Models\UserModel', false);
88

9-
// Create a shared instance of the model
9+
// Create a shared instance of the model.
1010
$userModel = model('App\Models\UserModel');
1111

12-
// Create shared instance with a supplied database connection
12+
// Create shared instance with a supplied database connection.
1313
// When no namespace is given, it will search through all namespaces
1414
// the system knows about and attempts to locate the UserModel class.
1515
$db = db_connect('custom');

user_guide_src/source/models/model/005.php

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,27 @@ class UserModel extends Model
1616

1717
protected $allowedFields = ['name', 'email'];
1818

19+
// Dates
1920
protected $useTimestamps = false;
21+
protected $dateFormat = 'datetime';
2022
protected $createdField = 'created_at';
2123
protected $updatedField = 'updated_at';
2224
protected $deletedField = 'deleted_at';
2325

24-
protected $validationRules = [];
25-
protected $validationMessages = [];
26-
protected $skipValidation = false;
26+
// Validation
27+
protected $validationRules = [];
28+
protected $validationMessages = [];
29+
protected $skipValidation = false;
30+
protected $cleanValidationRules = true;
31+
32+
// Callbacks
33+
protected $allowCallbacks = true;
34+
protected $beforeInsert = [];
35+
protected $afterInsert = [];
36+
protected $beforeUpdate = [];
37+
protected $afterUpdate = [];
38+
protected $beforeFind = [];
39+
protected $afterFind = [];
40+
protected $beforeDelete = [];
41+
protected $afterDelete = [];
2742
}
Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
11
<?php
22

3-
$users = $userModel->where('active', 1)
4-
->findAll();
3+
$users = $userModel->where('active', 1)->findAll();
Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
11
<?php
22

3-
$user = $userModel->where('deleted', 0)
4-
->first();
3+
$user = $userModel->where('deleted', 0)->first();

0 commit comments

Comments
 (0)