ÿŰÿàJFIFHHÿá .
BSA HACKER
Logo of a company Server : Apache
System : Linux nusantara.hosteko.com 4.18.0-553.16.1.lve.el8.x86_64 #1 SMP Tue Aug 13 17:45:03 UTC 2024 x86_64
User : koperas1 ( 1254)
PHP Version : 7.4.33
Disable Function : NONE
Directory :  /home/koperas1/www/userguide/models/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : /home/koperas1/www/userguide/models/model.html

<!DOCTYPE html>
<html class="writer-html4" lang="en" >
<head>
  <meta charset="utf-8" />
  
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  
  <title>Using CodeIgniter’s Model &mdash; CodeIgniter 4.1.1 documentation</title>
  

  
  <link rel="stylesheet" href="../_static/css/citheme.css" type="text/css" />
  <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

  
  
    <link rel="shortcut icon" href="../_static/favicon.ico"/>
  

  
  

  

  
  <!--[if lt IE 9]>
    <script src="../_static/js/html5shiv.min.js"></script>
  <![endif]-->
  
    
      <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
        <script type="text/javascript" src="../_static/jquery.js"></script>
        <script type="text/javascript" src="../_static/underscore.js"></script>
        <script type="text/javascript" src="../_static/doctools.js"></script>
        <script type="text/javascript" src="../_static/language_data.js"></script>
        <script type="text/javascript" src="../_static/js/citheme.js"></script>
        <script type="text/javascript" src="../_static/js/carbon.js"></script>
    
    <script type="text/javascript" src="../_static/js/theme.js"></script>

    
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="next" title="Using Entity Classes" href="entities.html" />
    <link rel="prev" title="Modeling Data" href="index.html" /> 
</head>

<body class="wy-body-for-nav">

   
  <div class="wy-grid-for-nav">
    
    <nav data-toggle="wy-nav-shift" class="wy-nav-side">
      <div class="wy-side-scroll">
        <div class="wy-side-nav-search"  style="background: #DD4814" >
          

          
            <a href="../index.html">
          

          
            
            <img src="../_static/ci-logo-text.png" class="logo" alt="Logo"/>
          
          </a>

          

          
<div role="search">
  <form id="rtd-search-form" class="wy-form" action="../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>
</div>

          
        </div>

        
        <div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation">
          
            
            
              
            
            
              <ul>
<li class="toctree-l1"><a class="reference internal" href="../intro/index.html">Welcome to CodeIgniter4</a><ul>
<li class="toctree-l2"><a class="reference internal" href="../intro/index.html">Welcome to CodeIgniter4</a></li>
<li class="toctree-l2"><a class="reference internal" href="../intro/requirements.html">Server Requirements</a></li>
<li class="toctree-l2"><a class="reference internal" href="../intro/credits.html">Credits</a></li>
<li class="toctree-l2"><a class="reference internal" href="../intro/psr.html">PSR Compliance</a></li>
</ul>
</li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../installation/index.html">Installation</a><ul>
<li class="toctree-l2"><a class="reference internal" href="../installation/installing_composer.html">Composer Installation</a></li>
<li class="toctree-l2"><a class="reference internal" href="../installation/installing_manual.html">Manual Installation</a></li>
<li class="toctree-l2"><a class="reference internal" href="../installation/running.html">Running Your App</a></li>
<li class="toctree-l2"><a class="reference internal" href="../installation/upgrading.html">Upgrading From a Previous Version</a></li>
<li class="toctree-l2"><a class="reference internal" href="../installation/troubleshooting.html">Troubleshooting</a></li>
<li class="toctree-l2"><a class="reference internal" href="../installation/repositories.html">CodeIgniter Repositories</a></li>
</ul>
</li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../tutorial/index.html">Build Your First Application</a><ul>
<li class="toctree-l2"><a class="reference internal" href="../tutorial/static_pages.html">Static pages</a></li>
<li class="toctree-l2"><a class="reference internal" href="../tutorial/news_section.html">News section</a></li>
<li class="toctree-l2"><a class="reference internal" href="../tutorial/create_news_items.html">Create news items</a></li>
<li class="toctree-l2"><a class="reference internal" href="../tutorial/conclusion.html">Conclusion</a></li>
</ul>
</li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../concepts/index.html">CodeIgniter4 Overview</a><ul>
<li class="toctree-l2"><a class="reference internal" href="../concepts/structure.html">Application Structure</a></li>
<li class="toctree-l2"><a class="reference internal" href="../concepts/mvc.html">Models, Views, and Controllers</a></li>
<li class="toctree-l2"><a class="reference internal" href="../concepts/autoloader.html">Autoloading Files</a></li>
<li class="toctree-l2"><a class="reference internal" href="../concepts/services.html">Services</a></li>
<li class="toctree-l2"><a class="reference internal" href="../concepts/factories.html">Factories</a></li>
<li class="toctree-l2"><a class="reference internal" href="../concepts/http.html">Working With HTTP Requests</a></li>
<li class="toctree-l2"><a class="reference internal" href="../concepts/security.html">Security Guidelines</a></li>
</ul>
</li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../general/index.html">General Topics</a><ul>
<li class="toctree-l2"><a class="reference internal" href="../general/configuration.html">Configuration</a></li>
<li class="toctree-l2"><a class="reference internal" href="../general/urls.html">CodeIgniter URLs</a></li>
<li class="toctree-l2"><a class="reference internal" href="../general/helpers.html">Helper Functions</a></li>
<li class="toctree-l2"><a class="reference internal" href="../general/common_functions.html">Global Functions and Constants</a></li>
<li class="toctree-l2"><a class="reference internal" href="../general/logging.html">Logging Information</a></li>
<li class="toctree-l2"><a class="reference internal" href="../general/errors.html">Error Handling</a></li>
<li class="toctree-l2"><a class="reference internal" href="../general/caching.html">Web Page Caching</a></li>
<li class="toctree-l2"><a class="reference internal" href="../general/ajax.html">AJAX Requests</a></li>
<li class="toctree-l2"><a class="reference internal" href="../general/modules.html">Code Modules</a></li>
<li class="toctree-l2"><a class="reference internal" href="../general/managing_apps.html">Managing your Applications</a></li>
<li class="toctree-l2"><a class="reference internal" href="../general/environments.html">Handling Multiple Environments</a></li>
</ul>
</li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../incoming/index.html">Controllers and Routing</a><ul>
<li class="toctree-l2"><a class="reference internal" href="../incoming/controllers.html">Controllers</a></li>
<li class="toctree-l2"><a class="reference internal" href="../incoming/routing.html">URI Routing</a></li>
<li class="toctree-l2"><a class="reference internal" href="../incoming/filters.html">Controller Filters</a></li>
<li class="toctree-l2"><a class="reference internal" href="../incoming/message.html">HTTP Messages</a></li>
<li class="toctree-l2"><a class="reference internal" href="../incoming/request.html">Request Class</a></li>
<li class="toctree-l2"><a class="reference internal" href="../incoming/incomingrequest.html">IncomingRequest Class</a></li>
<li class="toctree-l2"><a class="reference internal" href="../incoming/content_negotiation.html">Content Negotiation</a></li>
<li class="toctree-l2"><a class="reference internal" href="../incoming/methodspoofing.html">HTTP Method Spoofing</a></li>
<li class="toctree-l2"><a class="reference internal" href="../incoming/restful.html">RESTful Resource Handling</a></li>
</ul>
</li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../outgoing/index.html">Building Responses</a><ul>
<li class="toctree-l2"><a class="reference internal" href="../outgoing/views.html">Views</a></li>
<li class="toctree-l2"><a class="reference internal" href="../outgoing/view_cells.html">View Cells</a></li>
<li class="toctree-l2"><a class="reference internal" href="../outgoing/view_renderer.html">View Renderer</a></li>
<li class="toctree-l2"><a class="reference internal" href="../outgoing/view_layouts.html">View Layouts</a></li>
<li class="toctree-l2"><a class="reference internal" href="../outgoing/view_parser.html">View Parser</a></li>
<li class="toctree-l2"><a class="reference internal" href="../outgoing/table.html">HTML Table Class</a></li>
<li class="toctree-l2"><a class="reference internal" href="../outgoing/response.html">HTTP Responses</a></li>
<li class="toctree-l2"><a class="reference internal" href="../outgoing/api_responses.html">API Response Trait</a></li>
<li class="toctree-l2"><a class="reference internal" href="../outgoing/localization.html">Localization</a></li>
<li class="toctree-l2"><a class="reference internal" href="../outgoing/alternative_php.html">Alternate PHP Syntax for View Files</a></li>
</ul>
</li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../database/index.html">Working With Databases</a><ul>
<li class="toctree-l2"><a class="reference internal" href="../database/examples.html">Quick Start: Usage Examples</a></li>
<li class="toctree-l2"><a class="reference internal" href="../database/configuration.html">Database Configuration</a></li>
<li class="toctree-l2"><a class="reference internal" href="../database/connecting.html">Connecting to a Database</a></li>
<li class="toctree-l2"><a class="reference internal" href="../database/queries.html">Running Queries</a></li>
<li class="toctree-l2"><a class="reference internal" href="../database/results.html">Generating Query Results</a></li>
<li class="toctree-l2"><a class="reference internal" href="../database/helpers.html">Query Helper Functions</a></li>
<li class="toctree-l2"><a class="reference internal" href="../database/query_builder.html">Query Builder Class</a></li>
<li class="toctree-l2"><a class="reference internal" href="../database/transactions.html">Transactions</a></li>
<li class="toctree-l2"><a class="reference internal" href="../database/metadata.html">Getting MetaData</a></li>
<li class="toctree-l2"><a class="reference internal" href="../database/call_function.html">Custom Function Calls</a></li>
<li class="toctree-l2"><a class="reference internal" href="../database/events.html">Database Events</a></li>
<li class="toctree-l2"><a class="reference internal" href="../database/utilities.html">Database Utilities</a></li>
</ul>
</li>
</ul>
<ul class="current">
<li class="toctree-l1 current"><a class="reference internal" href="index.html">Modeling Data</a><ul class="current">
<li class="toctree-l2 current"><a class="current reference internal" href="#">Using CodeIgniter's Model</a></li>
<li class="toctree-l2"><a class="reference internal" href="entities.html">Using Entity Classes</a></li>
</ul>
</li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../dbmgmt/index.html">Managing Databases</a><ul>
<li class="toctree-l2"><a class="reference internal" href="../dbmgmt/forge.html">Database Manipulation with Database Forge</a></li>
<li class="toctree-l2"><a class="reference internal" href="../dbmgmt/migration.html">Database Migrations</a></li>
<li class="toctree-l2"><a class="reference internal" href="../dbmgmt/seeds.html">Database Seeding</a></li>
</ul>
</li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../libraries/index.html">Library Reference</a><ul>
<li class="toctree-l2"><a class="reference internal" href="../libraries/caching.html">Caching Driver</a></li>
<li class="toctree-l2"><a class="reference internal" href="../libraries/curlrequest.html">CURLRequest Class</a></li>
<li class="toctree-l2"><a class="reference internal" href="../libraries/email.html">Email Class</a></li>
<li class="toctree-l2"><a class="reference internal" href="../libraries/encryption.html">Encryption Service</a></li>
<li class="toctree-l2"><a class="reference internal" href="../libraries/files.html">Working with Files</a></li>
<li class="toctree-l2"><a class="reference internal" href="../libraries/honeypot.html">Honeypot Class</a></li>
<li class="toctree-l2"><a class="reference internal" href="../libraries/images.html">Image Manipulation Class</a></li>
<li class="toctree-l2"><a class="reference internal" href="../libraries/pagination.html">Pagination</a></li>
<li class="toctree-l2"><a class="reference internal" href="../libraries/security.html">Security</a></li>
<li class="toctree-l2"><a class="reference internal" href="../libraries/sessions.html">Session Library</a></li>
<li class="toctree-l2"><a class="reference internal" href="../libraries/throttler.html">Throttler</a></li>
<li class="toctree-l2"><a class="reference internal" href="../libraries/time.html">Times and Dates</a></li>
<li class="toctree-l2"><a class="reference internal" href="../libraries/typography.html">Typography</a></li>
<li class="toctree-l2"><a class="reference internal" href="../libraries/uploaded_files.html">Working with Uploaded Files</a></li>
<li class="toctree-l2"><a class="reference internal" href="../libraries/uri.html">Working with URIs</a></li>
<li class="toctree-l2"><a class="reference internal" href="../libraries/user_agent.html">User Agent Class</a></li>
<li class="toctree-l2"><a class="reference internal" href="../libraries/validation.html">Validation</a></li>
</ul>
</li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../helpers/index.html">Helpers</a><ul>
<li class="toctree-l2"><a class="reference internal" href="../helpers/array_helper.html">Array Helper</a></li>
<li class="toctree-l2"><a class="reference internal" href="../helpers/cookie_helper.html">Cookie Helper</a></li>
<li class="toctree-l2"><a class="reference internal" href="../helpers/date_helper.html">Date Helper</a></li>
<li class="toctree-l2"><a class="reference internal" href="../helpers/filesystem_helper.html">Filesystem Helper</a></li>
<li class="toctree-l2"><a class="reference internal" href="../helpers/form_helper.html">Form Helper</a></li>
<li class="toctree-l2"><a class="reference internal" href="../helpers/html_helper.html">HTML Helper</a></li>
<li class="toctree-l2"><a class="reference internal" href="../helpers/inflector_helper.html">Inflector Helper</a></li>
<li class="toctree-l2"><a class="reference internal" href="../helpers/number_helper.html">Number Helper</a></li>
<li class="toctree-l2"><a class="reference internal" href="../helpers/security_helper.html">Security Helper</a></li>
<li class="toctree-l2"><a class="reference internal" href="../helpers/test_helper.html">Test Helper</a></li>
<li class="toctree-l2"><a class="reference internal" href="../helpers/text_helper.html">Text Helper</a></li>
<li class="toctree-l2"><a class="reference internal" href="../helpers/url_helper.html">URL Helper</a></li>
<li class="toctree-l2"><a class="reference internal" href="../helpers/xml_helper.html">XML Helper</a></li>
</ul>
</li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../testing/index.html">Testing</a><ul>
<li class="toctree-l2"><a class="reference internal" href="../testing/overview.html">Getting Started</a></li>
<li class="toctree-l2"><a class="reference internal" href="../testing/database.html">Database</a></li>
<li class="toctree-l2"><a class="reference internal" href="../testing/fabricator.html">Generating Data</a></li>
<li class="toctree-l2"><a class="reference internal" href="../testing/controllers.html">Controller Testing</a></li>
<li class="toctree-l2"><a class="reference internal" href="../testing/feature.html">HTTP Testing</a></li>
<li class="toctree-l2"><a class="reference internal" href="../testing/benchmark.html">Benchmarking</a></li>
<li class="toctree-l2"><a class="reference internal" href="../testing/debugging.html">Debugging Your Application</a></li>
</ul>
</li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../cli/index.html">Command Line Usage</a><ul>
<li class="toctree-l2"><a class="reference internal" href="../cli/cli.html">Running via the Command Line</a></li>
<li class="toctree-l2"><a class="reference internal" href="../cli/cli_commands.html">Custom CLI Commands</a></li>
<li class="toctree-l2"><a class="reference internal" href="../cli/cli_generators.html">CLI Generators</a></li>
<li class="toctree-l2"><a class="reference internal" href="../cli/cli_library.html">CLI Library</a></li>
<li class="toctree-l2"><a class="reference internal" href="../cli/cli_request.html">CLIRequest Class</a></li>
</ul>
</li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../extending/index.html">Extending CodeIgniter</a><ul>
<li class="toctree-l2"><a class="reference internal" href="../extending/core_classes.html">Creating Core System Classes</a></li>
<li class="toctree-l2"><a class="reference internal" href="../extending/common.html">Replacing Common Functions</a></li>
<li class="toctree-l2"><a class="reference internal" href="../extending/events.html">Events</a></li>
<li class="toctree-l2"><a class="reference internal" href="../extending/basecontroller.html">Extending the Controller</a></li>
<li class="toctree-l2"><a class="reference internal" href="../extending/authentication.html">Authentication</a></li>
<li class="toctree-l2"><a class="reference internal" href="../extending/contributing.html">Contributing to CodeIgniter</a></li>
</ul>
</li>
</ul>

            
          
        </div>
        
      </div>
    </nav>

    <section data-toggle="wy-nav-shift" class="wy-nav-content-wrap">

      
      <nav class="wy-nav-top" aria-label="top navigation">
        
          <i data-toggle="wy-nav-top" class="fa fa-bars"></i>
          <a href="../index.html">CodeIgniter</a>
        
      </nav>


      <div class="wy-nav-content">
        
        <div class="rst-content">
        
          

















<div role="navigation" aria-label="breadcrumbs navigation">

  <ul class="wy-breadcrumbs">
    
      <li><a href="../index.html" class="icon icon-home"></a> &raquo;</li>
        
          <li><a href="index.html">Modeling Data</a> &raquo;</li>
        
      <li>Using CodeIgniter’s Model</li>
    
    
      <li class="wy-breadcrumbs-aside">
        
          
        
      </li>
    
  </ul>

  
  <hr/>
</div>
          <div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article">
           <div itemprop="articleBody">
            
  <div class="section" id="using-codeigniter-s-model">
<h1>Using CodeIgniter’s Model<a class="headerlink" href="#using-codeigniter-s-model" title="Permalink to this headline">¶</a></h1>
<div class="contents local topic" id="contents">
<ul class="simple">
<li><a class="reference internal" href="#models" id="id1">Models</a></li>
<li><a class="reference internal" href="#accessing-models" id="id2">Accessing Models</a></li>
<li><a class="reference internal" href="#codeigniter-s-model" id="id3">CodeIgniter’s Model</a></li>
<li><a class="reference internal" href="#creating-your-model" id="id4">Creating Your Model</a><ul>
<li><a class="reference internal" href="#connecting-to-the-database" id="id5">Connecting to the Database</a></li>
<li><a class="reference internal" href="#configuring-your-model" id="id6">Configuring Your Model</a></li>
</ul>
</li>
<li><a class="reference internal" href="#working-with-data" id="id7">Working With Data</a><ul>
<li><a class="reference internal" href="#finding-data" id="id8">Finding Data</a></li>
<li><a class="reference internal" href="#saving-data" id="id9">Saving Data</a></li>
<li><a class="reference internal" href="#deleting-data" id="id10">Deleting Data</a></li>
<li><a class="reference internal" href="#validating-data" id="id11">Validating Data</a></li>
<li><a class="reference internal" href="#retrieving-validation-rules" id="id12">Retrieving Validation Rules</a></li>
<li><a class="reference internal" href="#validation-placeholders" id="id13">Validation Placeholders</a></li>
<li><a class="reference internal" href="#protecting-fields" id="id14">Protecting Fields</a></li>
<li><a class="reference internal" href="#working-with-query-builder" id="id15">Working With Query Builder</a></li>
<li><a class="reference internal" href="#runtime-return-type-changes" id="id16">Runtime Return Type Changes</a></li>
<li><a class="reference internal" href="#processing-large-amounts-of-data" id="id17">Processing Large Amounts of Data</a></li>
</ul>
</li>
<li><a class="reference internal" href="#model-events" id="id18">Model Events</a><ul>
<li><a class="reference internal" href="#defining-callbacks" id="id19">Defining Callbacks</a></li>
<li><a class="reference internal" href="#specifying-callbacks-to-run" id="id20">Specifying Callbacks To Run</a></li>
<li><a class="reference internal" href="#event-parameters" id="id21">Event Parameters</a></li>
<li><a class="reference internal" href="#modifying-find-data" id="id22">Modifying Find* Data</a></li>
</ul>
</li>
<li><a class="reference internal" href="#manual-model-creation" id="id23">Manual Model Creation</a></li>
</ul>
</div>
<div class="section" id="models">
<h2><a class="toc-backref" href="#id1">Models</a><a class="headerlink" href="#models" title="Permalink to this headline">¶</a></h2>
<p>Models provide a way to interact with a specific table in your database. They come out of the box with helper
methods for much of the standard ways you would need to interact with a database table, including finding records,
updating records, deleting records, and more.</p>
</div>
<div class="section" id="accessing-models">
<h2><a class="toc-backref" href="#id2">Accessing Models</a><a class="headerlink" href="#accessing-models" title="Permalink to this headline">¶</a></h2>
<p>Models are typically stored in the <code class="docutils literal notranslate"><span class="pre">app/Models</span></code> directory. They should have a namespace that matches their
location within the directory, like <code class="docutils literal notranslate"><span class="pre">namespace</span> <span class="pre">App\Models</span></code>.</p>
<p>You can access models within your classes by creating a new instance or using the <code class="docutils literal notranslate"><span class="pre">model()</span></code> helper function.</p>
<div class="highlight-html+php notranslate"><div class="highlight"><pre><span></span><span class="c1">// Create a new class manually</span>
<span class="nv">$userModel</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">\App\Models\UserModel</span><span class="p">();</span>

<span class="c1">// Create a new class with the model function</span>
<span class="nv">$userModel</span> <span class="o">=</span> <span class="nx">model</span><span class="p">(</span><span class="s1">&#39;App\Models\UserModel&#39;</span><span class="p">,</span> <span class="k">false</span><span class="p">);</span>

<span class="c1">// Create a shared instance of the model</span>
<span class="nv">$userModel</span> <span class="o">=</span> <span class="nx">model</span><span class="p">(</span><span class="s1">&#39;App\Models\UserModel&#39;</span><span class="p">);</span>

<span class="c1">// Create shared instance with a supplied database connection</span>
<span class="c1">// When no namespace is given, it will search through all namespaces</span>
<span class="c1">// the system knows about and attempt to located the UserModel class.</span>
<span class="nv">$db</span> <span class="o">=</span> <span class="nx">db_connect</span><span class="p">(</span><span class="s1">&#39;custom&#39;</span><span class="p">);</span>
<span class="nv">$userModel</span> <span class="o">=</span> <span class="nx">model</span><span class="p">(</span><span class="s1">&#39;UserModel&#39;</span><span class="p">,</span> <span class="k">true</span><span class="p">,</span> <span class="nv">$db</span><span class="p">);</span>
</pre></div>
</div>
</div>
<div class="section" id="codeigniter-s-model">
<h2><a class="toc-backref" href="#id3">CodeIgniter’s Model</a><a class="headerlink" href="#codeigniter-s-model" title="Permalink to this headline">¶</a></h2>
<p>CodeIgniter does provide a model class that provides a few nice features, including:</p>
<ul class="simple">
<li>automatic database connection</li>
<li>basic CRUD methods</li>
<li>in-model validation</li>
<li>automatic pagination</li>
<li>and more</li>
</ul>
<p>This class provides a solid base from which to build your own models, allowing you to
rapidly build out your application’s model layer.</p>
</div>
<div class="section" id="creating-your-model">
<h2><a class="toc-backref" href="#id4">Creating Your Model</a><a class="headerlink" href="#creating-your-model" title="Permalink to this headline">¶</a></h2>
<p>To take advantage of CodeIgniter’s model, you would simply create a new model class
that extends <code class="docutils literal notranslate"><span class="pre">CodeIgniter\Model</span></code>:</p>
<div class="highlight-html+php notranslate"><div class="highlight"><pre><span></span><span class="o">&lt;?</span><span class="nx">php</span>

<span class="k">namespace</span> <span class="nx">App\Models</span><span class="p">;</span>

<span class="k">use</span> <span class="nx">CodeIgniter\Model</span><span class="p">;</span>

<span class="k">class</span> <span class="nc">UserModel</span> <span class="k">extends</span> <span class="nx">Model</span>
<span class="p">{</span>
    <span class="c1">// ...</span>
<span class="p">}</span>
</pre></div>
</div>
<p>This empty class provides convenient access to the database connection, the Query Builder,
and a number of additional convenience methods.</p>
<div class="section" id="connecting-to-the-database">
<h3><a class="toc-backref" href="#id5">Connecting to the Database</a><a class="headerlink" href="#connecting-to-the-database" title="Permalink to this headline">¶</a></h3>
<p>When the class is first instantiated, if no database connection instance is passed to the constructor,
it will automatically connect to the default database group, as set in the configuration. You can
modify which group is used on a per-model basis by adding the DBGroup property to your class.
This ensures that within the model any references to <code class="docutils literal notranslate"><span class="pre">$this-&gt;db</span></code> are made through the appropriate
connection.</p>
<div class="highlight-html+php notranslate"><div class="highlight"><pre><span></span><span class="o">&lt;?</span><span class="nx">php</span>

<span class="k">namespace</span> <span class="nx">App\Models</span><span class="p">;</span>

<span class="k">use</span> <span class="nx">CodeIgniter\Model</span><span class="p">;</span>

<span class="k">class</span> <span class="nc">UserModel</span> <span class="k">extends</span> <span class="nx">Model</span>
<span class="p">{</span>
    <span class="k">protected</span> <span class="nv">$DBGroup</span> <span class="o">=</span> <span class="s1">&#39;group_name&#39;</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
<p>You would replace “group_name” with the name of a defined database group from the database
configuration file.</p>
</div>
<div class="section" id="configuring-your-model">
<h3><a class="toc-backref" href="#id6">Configuring Your Model</a><a class="headerlink" href="#configuring-your-model" title="Permalink to this headline">¶</a></h3>
<p>The model class has a few configuration options that can be set to allow the class’ methods
to work seamlessly for you. The first two are used by all of the CRUD methods to determine
what table to use and how we can find the required records:</p>
<div class="highlight-html+php notranslate"><div class="highlight"><pre><span></span><span class="o">&lt;?</span><span class="nx">php</span>

<span class="k">namespace</span> <span class="nx">App\Models</span><span class="p">;</span>

<span class="k">use</span> <span class="nx">CodeIgniter\Model</span><span class="p">;</span>

<span class="k">class</span> <span class="nc">UserModel</span> <span class="k">extends</span> <span class="nx">Model</span>
<span class="p">{</span>
    <span class="k">protected</span> <span class="nv">$table</span>      <span class="o">=</span> <span class="s1">&#39;users&#39;</span><span class="p">;</span>
    <span class="k">protected</span> <span class="nv">$primaryKey</span> <span class="o">=</span> <span class="s1">&#39;id&#39;</span><span class="p">;</span>

    <span class="k">protected</span> <span class="nv">$useAutoIncrement</span> <span class="o">=</span> <span class="k">true</span><span class="p">;</span>

    <span class="k">protected</span> <span class="nv">$returnType</span>     <span class="o">=</span> <span class="s1">&#39;array&#39;</span><span class="p">;</span>
    <span class="k">protected</span> <span class="nv">$useSoftDeletes</span> <span class="o">=</span> <span class="k">true</span><span class="p">;</span>

    <span class="k">protected</span> <span class="nv">$allowedFields</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;name&#39;</span><span class="p">,</span> <span class="s1">&#39;email&#39;</span><span class="p">];</span>

    <span class="k">protected</span> <span class="nv">$useTimestamps</span> <span class="o">=</span> <span class="k">false</span><span class="p">;</span>
    <span class="k">protected</span> <span class="nv">$createdField</span>  <span class="o">=</span> <span class="s1">&#39;created_at&#39;</span><span class="p">;</span>
    <span class="k">protected</span> <span class="nv">$updatedField</span>  <span class="o">=</span> <span class="s1">&#39;updated_at&#39;</span><span class="p">;</span>
    <span class="k">protected</span> <span class="nv">$deletedField</span>  <span class="o">=</span> <span class="s1">&#39;deleted_at&#39;</span><span class="p">;</span>

    <span class="k">protected</span> <span class="nv">$validationRules</span>    <span class="o">=</span> <span class="p">[];</span>
    <span class="k">protected</span> <span class="nv">$validationMessages</span> <span class="o">=</span> <span class="p">[];</span>
    <span class="k">protected</span> <span class="nv">$skipValidation</span>     <span class="o">=</span> <span class="k">false</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
<p><strong>$table</strong></p>
<p>Specifies the database table that this model primarily works with. This only applies to the
built-in CRUD methods. You are not restricted to using only this table in your own
queries.</p>
<p><strong>$primaryKey</strong></p>
<p>This is the name of the column that uniquely identifies the records in this table. This
does not necessarily have to match the primary key that is specified in the database, but
is used with methods like <code class="docutils literal notranslate"><span class="pre">find()</span></code> to know what column to match the specified value to.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">All Models must have a primaryKey specified to allow all of the features to work
as expected.</p>
</div>
<p><strong>$useAutoIncrement</strong></p>
<p>Specifies if the table uses an auto-increment feature for <code class="docutils literal notranslate"><span class="pre">$primaryKey</span></code>. If set to <code class="docutils literal notranslate"><span class="pre">false</span></code>
then you are responsible for providing primary key value for every record in the table. This
feature may be handy when we want to implement 1:1 relation or use UUIDs for our model.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">If you set <code class="docutils literal notranslate"><span class="pre">$useAutoIncrement</span></code> to <code class="docutils literal notranslate"><span class="pre">false</span></code> then make sure to set your primary
key in the database to <code class="docutils literal notranslate"><span class="pre">unique</span></code>. This way you will make sure that all of Model’s features
will still work the same as before.</p>
</div>
<p><strong>$returnType</strong></p>
<p>The Model’s CRUD methods will take a step of work away from you and automatically return
the resulting data, instead of the Result object. This setting allows you to define
the type of data that is returned. Valid values are ‘array’, ‘object’, or the fully
qualified name of a class that can be used with the Result object’s getCustomResultObject()
method.</p>
<p><strong>$useSoftDeletes</strong></p>
<p>If true, then any delete* method calls will set <code class="docutils literal notranslate"><span class="pre">deleted_at</span></code> in the database, instead of
actually deleting the row. This can preserve data when it might be referenced elsewhere, or
can maintain a “recycle bin” of objects that can be restored, or even simply preserve it as
part of a security trail. If true, the find* methods will only return non-deleted rows, unless
the withDeleted() method is called prior to calling the find* method.</p>
<p>This requires either a DATETIME or INTEGER field in the database as per the model’s
$dateFormat setting. The default field name is <code class="docutils literal notranslate"><span class="pre">deleted_at</span></code> however this name can be
configured to any name of your choice by using $deletedField property.</p>
<p><strong>$allowedFields</strong></p>
<p>This array should be updated with the field names that can be set during save, insert, or
update methods. Any field names other than these will be discarded. This helps to protect
against just taking input from a form and throwing it all at the model, resulting in
potential mass assignment vulnerabilities.</p>
<p><strong>$useTimestamps</strong></p>
<p>This boolean value determines whether the current date is automatically added to all inserts
and updates. If true, will set the current time in the format specified by $dateFormat. This
requires that the table have columns named ‘created_at’ and ‘updated_at’ in the appropriate
data type.</p>
<p><strong>$createdField</strong></p>
<p>Specifies which database field to use for data record create timestamp.
Leave it empty to avoid updating it (even if <code class="docutils literal notranslate"><span class="pre">$useTimestamps</span></code> is enabled)</p>
<p><strong>$updatedField</strong></p>
<p>Specifies which database field should use for keep data record update timestamp.
Leave it empty to avoid update it (even useTimestamps is enabled)</p>
<p><strong>$dateFormat</strong></p>
<p>This value works with $useTimestamps and $useSoftDeletes to ensure that the correct type of
date value gets inserted into the database. By default, this creates DATETIME values, but
valid options are: datetime, date, or int (a PHP timestamp). Using ‘useSoftDeletes’ or
‘useTimestamps’ with an invalid or missing dateFormat will cause an exception.</p>
<p><strong>$validationRules</strong></p>
<p>Contains either an array of validation rules as described in <a class="reference internal" href="../libraries/validation.html#validation-array"><span class="std std-ref">How to save your rules</span></a>
or a string containing the name of a validation group, as described in the same section.
Described in more detail below.</p>
<p><strong>$validationMessages</strong></p>
<p>Contains an array of custom error messages that should be used during validation, as
described in <a class="reference internal" href="../libraries/validation.html#validation-custom-errors"><span class="std std-ref">Setting Custom Error Messages</span></a>. Described in more detail below.</p>
<p><strong>$skipValidation</strong></p>
<p>Whether validation should be skipped during all <code class="docutils literal notranslate"><span class="pre">inserts</span></code> and <code class="docutils literal notranslate"><span class="pre">updates</span></code>. The default
value is false, meaning that data will always attempt to be validated. This is
primarily used by the <code class="docutils literal notranslate"><span class="pre">skipValidation()</span></code> method, but may be changed to <code class="docutils literal notranslate"><span class="pre">true</span></code> so
this model will never validate.</p>
<p><strong>$beforeInsert</strong>
<strong>$afterInsert</strong>
<strong>$beforeUpdate</strong>
<strong>$afterUpdate</strong>
<strong>$afterFind</strong>
<strong>$afterDelete</strong></p>
<p>These arrays allow you to specify callback methods that will be run on the data at the
time specified in the property name.</p>
<p><strong>$allowCallbacks</strong></p>
<p>Whether the callbacks defined above should be used.</p>
</div>
</div>
<div class="section" id="working-with-data">
<h2><a class="toc-backref" href="#id7">Working With Data</a><a class="headerlink" href="#working-with-data" title="Permalink to this headline">¶</a></h2>
<div class="section" id="finding-data">
<h3><a class="toc-backref" href="#id8">Finding Data</a><a class="headerlink" href="#finding-data" title="Permalink to this headline">¶</a></h3>
<p>Several functions are provided for doing basic CRUD work on your tables, including find(),
insert(), update(), delete() and more.</p>
<p><strong>find()</strong></p>
<p>Returns a single row where the primary key matches the value passed in as the first parameter:</p>
<div class="highlight-html+php notranslate"><div class="highlight"><pre><span></span><span class="nv">$user</span> <span class="o">=</span> <span class="nv">$userModel</span><span class="o">-&gt;</span><span class="na">find</span><span class="p">(</span><span class="nv">$user_id</span><span class="p">);</span>
</pre></div>
</div>
<p>The value is returned in the format specified in $returnType.</p>
<p>You can specify more than one row to return by passing an array of primaryKey values instead
of just one:</p>
<div class="highlight-html+php notranslate"><div class="highlight"><pre><span></span><span class="nv">$users</span> <span class="o">=</span> <span class="nv">$userModel</span><span class="o">-&gt;</span><span class="na">find</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">]);</span>
</pre></div>
</div>
<p>If no parameters are passed in, will return all rows in that model’s table, effectively acting
like findAll(), though less explicit.</p>
<p><strong>findColumn()</strong></p>
<p>Returns null or an indexed array of column values:</p>
<div class="highlight-html+php notranslate"><div class="highlight"><pre><span></span><span class="nv">$user</span> <span class="o">=</span> <span class="nv">$userModel</span><span class="o">-&gt;</span><span class="na">findColumn</span><span class="p">(</span><span class="nv">$column_name</span><span class="p">);</span>
</pre></div>
</div>
<p>$column_name should be a name of single column else you will get the DataException.</p>
<p><strong>findAll()</strong></p>
<p>Returns all results:</p>
<div class="highlight-html+php notranslate"><div class="highlight"><pre><span></span><span class="nv">$users</span> <span class="o">=</span> <span class="nv">$userModel</span><span class="o">-&gt;</span><span class="na">findAll</span><span class="p">();</span>
</pre></div>
</div>
<p>This query may be modified by interjecting Query Builder commands as needed prior to calling this method:</p>
<div class="highlight-html+php notranslate"><div class="highlight"><pre><span></span><span class="nv">$users</span> <span class="o">=</span> <span class="nv">$userModel</span><span class="o">-&gt;</span><span class="na">where</span><span class="p">(</span><span class="s1">&#39;active&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
                   <span class="o">-&gt;</span><span class="na">findAll</span><span class="p">();</span>
</pre></div>
</div>
<p>You can pass in a limit and offset values as the first and second
parameters, respectively:</p>
<div class="highlight-html+php notranslate"><div class="highlight"><pre><span></span><span class="nv">$users</span> <span class="o">=</span> <span class="nv">$userModel</span><span class="o">-&gt;</span><span class="na">findAll</span><span class="p">(</span><span class="nv">$limit</span><span class="p">,</span> <span class="nv">$offset</span><span class="p">);</span>
</pre></div>
</div>
<p><strong>first()</strong></p>
<p>Returns the first row in the result set. This is best used in combination with the query builder.</p>
<div class="highlight-html+php notranslate"><div class="highlight"><pre><span></span><span class="nv">$user</span> <span class="o">=</span> <span class="nv">$userModel</span><span class="o">-&gt;</span><span class="na">where</span><span class="p">(</span><span class="s1">&#39;deleted&#39;</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span>
                  <span class="o">-&gt;</span><span class="na">first</span><span class="p">();</span>
</pre></div>
</div>
<p><strong>withDeleted()</strong></p>
<p>If $useSoftDeletes is true, then the find* methods will not return any rows where ‘deleted_at IS NOT NULL’.
To temporarily override this, you can use the withDeleted() method prior to calling the find* method.</p>
<div class="highlight-html+php notranslate"><div class="highlight"><pre><span></span><span class="c1">// Only gets non-deleted rows (deleted = 0)</span>
<span class="nv">$activeUsers</span> <span class="o">=</span> <span class="nv">$userModel</span><span class="o">-&gt;</span><span class="na">findAll</span><span class="p">();</span>

<span class="c1">// Gets all rows</span>
<span class="nv">$allUsers</span> <span class="o">=</span> <span class="nv">$userModel</span><span class="o">-&gt;</span><span class="na">withDeleted</span><span class="p">()</span>
                      <span class="o">-&gt;</span><span class="na">findAll</span><span class="p">();</span>
</pre></div>
</div>
<p><strong>onlyDeleted()</strong></p>
<p>Whereas withDeleted() will return both deleted and not-deleted rows, this method modifies
the next find* methods to return only soft deleted rows:</p>
<div class="highlight-html+php notranslate"><div class="highlight"><pre><span></span><span class="nv">$deletedUsers</span> <span class="o">=</span> <span class="nv">$userModel</span><span class="o">-&gt;</span><span class="na">onlyDeleted</span><span class="p">()</span>
                          <span class="o">-&gt;</span><span class="na">findAll</span><span class="p">();</span>
</pre></div>
</div>
</div>
<div class="section" id="saving-data">
<h3><a class="toc-backref" href="#id9">Saving Data</a><a class="headerlink" href="#saving-data" title="Permalink to this headline">¶</a></h3>
<p><strong>insert()</strong></p>
<p>An associative array of data is passed into this method as the only parameter to create a new
row of data in the database. The array’s keys must match the name of the columns in a $table, while
the array’s values are the values to save for that key:</p>
<div class="highlight-html+php notranslate"><div class="highlight"><pre><span></span><span class="nv">$data</span> <span class="o">=</span> <span class="p">[</span>
    <span class="s1">&#39;username&#39;</span> <span class="o">=&gt;</span> <span class="s1">&#39;darth&#39;</span><span class="p">,</span>
    <span class="s1">&#39;email&#39;</span>    <span class="o">=&gt;</span> <span class="s1">&#39;d.vader@theempire.com&#39;</span>
<span class="p">];</span>

<span class="nv">$userModel</span><span class="o">-&gt;</span><span class="na">insert</span><span class="p">(</span><span class="nv">$data</span><span class="p">);</span>
</pre></div>
</div>
<p><strong>update()</strong></p>
<p>Updates an existing record in the database. The first parameter is the $primaryKey of the record to update.
An associative array of data is passed into this method as the second parameter. The array’s keys must match the name
of the columns in a $table, while the array’s values are the values to save for that key:</p>
<div class="highlight-html+php notranslate"><div class="highlight"><pre><span></span><span class="nv">$data</span> <span class="o">=</span> <span class="p">[</span>
    <span class="s1">&#39;username&#39;</span> <span class="o">=&gt;</span> <span class="s1">&#39;darth&#39;</span><span class="p">,</span>
    <span class="s1">&#39;email&#39;</span>    <span class="o">=&gt;</span> <span class="s1">&#39;d.vader@theempire.com&#39;</span>
<span class="p">];</span>

<span class="nv">$userModel</span><span class="o">-&gt;</span><span class="na">update</span><span class="p">(</span><span class="nv">$id</span><span class="p">,</span> <span class="nv">$data</span><span class="p">);</span>
</pre></div>
</div>
<p>Multiple records may be updated with a single call by passing an array of primary keys as the first parameter:</p>
<div class="highlight-html+php notranslate"><div class="highlight"><pre><span></span><span class="nv">$data</span> <span class="o">=</span> <span class="p">[</span>
    <span class="s1">&#39;active&#39;</span> <span class="o">=&gt;</span> <span class="mi">1</span>
<span class="p">];</span>

<span class="nv">$userModel</span><span class="o">-&gt;</span><span class="na">update</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">],</span> <span class="nv">$data</span><span class="p">);</span>
</pre></div>
</div>
<p>When you need a more flexible solution, you can leave the parameters empty and it functions like the Query Builder’s
update command, with the added benefit of validation, events, etc:</p>
<div class="highlight-html+php notranslate"><div class="highlight"><pre><span></span><span class="nv">$userModel</span>
    <span class="o">-&gt;</span><span class="na">whereIn</span><span class="p">(</span><span class="s1">&#39;id&#39;</span><span class="p">,</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">])</span>
    <span class="o">-&gt;</span><span class="na">set</span><span class="p">([</span><span class="s1">&#39;active&#39;</span> <span class="o">=&gt;</span> <span class="mi">1</span><span class="p">])</span>
    <span class="o">-&gt;</span><span class="na">update</span><span class="p">();</span>
</pre></div>
</div>
<p><strong>save()</strong></p>
<p>This is a wrapper around the insert() and update() methods that handle inserting or updating the record
automatically, based on whether it finds an array key matching the $primaryKey value:</p>
<div class="highlight-html+php notranslate"><div class="highlight"><pre><span></span><span class="c1">// Defined as a model property</span>
<span class="nv">$primaryKey</span> <span class="o">=</span> <span class="s1">&#39;id&#39;</span><span class="p">;</span>

<span class="c1">// Does an insert()</span>
<span class="nv">$data</span> <span class="o">=</span> <span class="p">[</span>
    <span class="s1">&#39;username&#39;</span> <span class="o">=&gt;</span> <span class="s1">&#39;darth&#39;</span><span class="p">,</span>
    <span class="s1">&#39;email&#39;</span>    <span class="o">=&gt;</span> <span class="s1">&#39;d.vader@theempire.com&#39;</span>
<span class="p">];</span>

<span class="nv">$userModel</span><span class="o">-&gt;</span><span class="na">save</span><span class="p">(</span><span class="nv">$data</span><span class="p">);</span>

<span class="c1">// Performs an update, since the primary key, &#39;id&#39;, is found.</span>
<span class="nv">$data</span> <span class="o">=</span> <span class="p">[</span>
    <span class="s1">&#39;id&#39;</span>       <span class="o">=&gt;</span> <span class="mi">3</span><span class="p">,</span>
    <span class="s1">&#39;username&#39;</span> <span class="o">=&gt;</span> <span class="s1">&#39;darth&#39;</span><span class="p">,</span>
    <span class="s1">&#39;email&#39;</span>    <span class="o">=&gt;</span> <span class="s1">&#39;d.vader@theempire.com&#39;</span>
<span class="p">];</span>
<span class="nv">$userModel</span><span class="o">-&gt;</span><span class="na">save</span><span class="p">(</span><span class="nv">$data</span><span class="p">);</span>
</pre></div>
</div>
<p>The save method also can make working with custom class result objects much simpler by recognizing a non-simple
object and grabbing its public and protected values into an array, which is then passed to the appropriate
insert or update method. This allows you to work with Entity classes in a very clean way. Entity classes are
simple classes that represent a single instance of an object type, like a user, a blog post, job, etc. This
class is responsible for maintaining the business logic surrounding the object itself, like formatting
elements in a certain way, etc. They shouldn’t have any idea about how they are saved to the database. At their
simplest, they might look like this:</p>
<div class="highlight-html+php notranslate"><div class="highlight"><pre><span></span><span class="k">namespace</span> <span class="nx">App\Entities</span><span class="p">;</span>

<span class="k">class</span> <span class="nc">Job</span>
<span class="p">{</span>
    <span class="k">protected</span> <span class="nv">$id</span><span class="p">;</span>
    <span class="k">protected</span> <span class="nv">$name</span><span class="p">;</span>
    <span class="k">protected</span> <span class="nv">$description</span><span class="p">;</span>

    <span class="k">public</span> <span class="k">function</span> <span class="fm">__get</span><span class="p">(</span><span class="nv">$key</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="k">if</span> <span class="p">(</span><span class="nb">property_exists</span><span class="p">(</span><span class="nv">$this</span><span class="p">,</span> <span class="nv">$key</span><span class="p">))</span>
        <span class="p">{</span>
            <span class="k">return</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="nv">$key</span><span class="p">;</span>
        <span class="p">}</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="fm">__set</span><span class="p">(</span><span class="nv">$key</span><span class="p">,</span> <span class="nv">$value</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="k">if</span> <span class="p">(</span><span class="nb">property_exists</span><span class="p">(</span><span class="nv">$this</span><span class="p">,</span> <span class="nv">$key</span><span class="p">))</span>
        <span class="p">{</span>
            <span class="nv">$this</span><span class="o">-&gt;</span><span class="nv">$key</span> <span class="o">=</span> <span class="nv">$value</span><span class="p">;</span>
        <span class="p">}</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>A very simple model to work with this might look like:</p>
<div class="highlight-html+php notranslate"><div class="highlight"><pre><span></span><span class="k">use</span> <span class="nx">CodeIgniter\Model</span><span class="p">;</span>

<span class="k">class</span> <span class="nc">JobModel</span> <span class="k">extends</span> <span class="nx">Model</span>
<span class="p">{</span>
    <span class="k">protected</span> <span class="nv">$table</span> <span class="o">=</span> <span class="s1">&#39;jobs&#39;</span><span class="p">;</span>
    <span class="k">protected</span> <span class="nv">$returnType</span> <span class="o">=</span> <span class="s1">&#39;\App\Entities\Job&#39;</span><span class="p">;</span>
    <span class="k">protected</span> <span class="nv">$allowedFields</span> <span class="o">=</span> <span class="p">[</span>
        <span class="s1">&#39;name&#39;</span><span class="p">,</span> <span class="s1">&#39;description&#39;</span>
    <span class="p">];</span>
<span class="p">}</span>
</pre></div>
</div>
<p>This model works with data from the <code class="docutils literal notranslate"><span class="pre">jobs</span></code> table, and returns all results as an instance of <code class="docutils literal notranslate"><span class="pre">App\Entities\Job</span></code>.
When you need to persist that record to the database, you will need to either write custom methods, or use the
model’s <code class="docutils literal notranslate"><span class="pre">save()</span></code> method to inspect the class, grab any public and private properties, and save them to the database:</p>
<div class="highlight-html+php notranslate"><div class="highlight"><pre><span></span><span class="c1">// Retrieve a Job instance</span>
<span class="nv">$job</span> <span class="o">=</span> <span class="nv">$model</span><span class="o">-&gt;</span><span class="na">find</span><span class="p">(</span><span class="mi">15</span><span class="p">);</span>

<span class="c1">// Make some changes</span>
<span class="nv">$job</span><span class="o">-&gt;</span><span class="na">name</span> <span class="o">=</span> <span class="s2">&quot;Foobar&quot;</span><span class="p">;</span>

<span class="c1">// Save the changes</span>
<span class="nv">$model</span><span class="o">-&gt;</span><span class="na">save</span><span class="p">(</span><span class="nv">$job</span><span class="p">);</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">If you find yourself working with Entities a lot, CodeIgniter provides a built-in <a class="reference internal" href="entities.html"><span class="doc">Entity class</span></a>
that provides several handy features that make developing Entities simpler.</p>
</div>
</div>
<div class="section" id="deleting-data">
<h3><a class="toc-backref" href="#id10">Deleting Data</a><a class="headerlink" href="#deleting-data" title="Permalink to this headline">¶</a></h3>
<p><strong>delete()</strong></p>
<p>Takes a primary key value as the first parameter and deletes the matching record from the model’s table:</p>
<div class="highlight-html+php notranslate"><div class="highlight"><pre><span></span><span class="nv">$userModel</span><span class="o">-&gt;</span><span class="na">delete</span><span class="p">(</span><span class="mi">12</span><span class="p">);</span>
</pre></div>
</div>
<p>If the model’s $useSoftDeletes value is true, this will update the row to set <code class="docutils literal notranslate"><span class="pre">deleted_at</span></code> to the current
date and time. You can force a permanent delete by setting the second parameter as true.</p>
<p>An array of primary keys can be passed in as the first parameter to delete multiple records at once:</p>
<div class="highlight-html+php notranslate"><div class="highlight"><pre><span></span><span class="nv">$userModel</span><span class="o">-&gt;</span><span class="na">delete</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">]);</span>
</pre></div>
</div>
<p>If no parameters are passed in, will act like the Query Builder’s delete method, requiring a where call
previously:</p>
<div class="highlight-html+php notranslate"><div class="highlight"><pre><span></span><span class="nv">$userModel</span><span class="o">-&gt;</span><span class="na">where</span><span class="p">(</span><span class="s1">&#39;id&#39;</span><span class="p">,</span> <span class="mi">12</span><span class="p">)</span><span class="o">-&gt;</span><span class="na">delete</span><span class="p">();</span>
</pre></div>
</div>
<p><strong>purgeDeleted()</strong></p>
<p>Cleans out the database table by permanently removing all rows that have ‘deleted_at IS NOT NULL’.</p>
<div class="highlight-html+php notranslate"><div class="highlight"><pre><span></span><span class="nv">$userModel</span><span class="o">-&gt;</span><span class="na">purgeDeleted</span><span class="p">();</span>
</pre></div>
</div>
</div>
<div class="section" id="validating-data">
<h3><a class="toc-backref" href="#id11">Validating Data</a><a class="headerlink" href="#validating-data" title="Permalink to this headline">¶</a></h3>
<p>For many people, validating data in the model is the preferred way to ensure the data is kept to a single
standard, without duplicating code. The Model class provides a way to automatically have all data validated
prior to saving to the database with the <code class="docutils literal notranslate"><span class="pre">insert()</span></code>, <code class="docutils literal notranslate"><span class="pre">update()</span></code>, or <code class="docutils literal notranslate"><span class="pre">save()</span></code> methods.</p>
<p>The first step is to fill out the <code class="docutils literal notranslate"><span class="pre">$validationRules</span></code> class property with the fields and rules that should
be applied. If you have custom error message that you want to use, place them in the <code class="docutils literal notranslate"><span class="pre">$validationMessages</span></code> array:</p>
<div class="highlight-html+php notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">UserModel</span> <span class="k">extends</span> <span class="nx">Model</span>
<span class="p">{</span>
    <span class="k">protected</span> <span class="nv">$validationRules</span>    <span class="o">=</span> <span class="p">[</span>
        <span class="s1">&#39;username&#39;</span>     <span class="o">=&gt;</span> <span class="s1">&#39;required|alpha_numeric_space|min_length[3]&#39;</span><span class="p">,</span>
        <span class="s1">&#39;email&#39;</span>        <span class="o">=&gt;</span> <span class="s1">&#39;required|valid_email|is_unique[users.email]&#39;</span><span class="p">,</span>
        <span class="s1">&#39;password&#39;</span>     <span class="o">=&gt;</span> <span class="s1">&#39;required|min_length[8]&#39;</span><span class="p">,</span>
        <span class="s1">&#39;pass_confirm&#39;</span> <span class="o">=&gt;</span> <span class="s1">&#39;required_with[password]|matches[password]&#39;</span>
    <span class="p">];</span>

    <span class="k">protected</span> <span class="nv">$validationMessages</span> <span class="o">=</span> <span class="p">[</span>
        <span class="s1">&#39;email&#39;</span>        <span class="o">=&gt;</span> <span class="p">[</span>
            <span class="s1">&#39;is_unique&#39;</span> <span class="o">=&gt;</span> <span class="s1">&#39;Sorry. That email has already been taken. Please choose another.&#39;</span>
        <span class="p">]</span>
    <span class="p">];</span>
<span class="p">}</span>
</pre></div>
</div>
<p>The other way to set the validation rules to fields by functions,</p>
<dl class="function">
<dt id="setValidationRule">
<code class="descname">setValidationRule</code><span class="sig-paren">(</span><em>$field</em>, <em>$fieldRules</em><span class="sig-paren">)</span><a class="headerlink" href="#setValidationRule" title="Permalink to this definition">¶</a></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple">
<li><strong>$field</strong> (<em>string</em>) – </li>
<li><strong>$fieldRules</strong> (<em>array</em>) – </li>
</ul>
</td>
</tr>
</tbody>
</table>
<p>This function will set the field validation rules.</p>
<p>Usage example:</p>
<div class="highlight-html+php notranslate"><div class="highlight"><pre><span></span><span class="nv">$fieldName</span> <span class="o">=</span> <span class="s1">&#39;username&#39;</span><span class="p">;</span>
<span class="nv">$fieldRules</span> <span class="o">=</span> <span class="s1">&#39;required|alpha_numeric_space|min_length[3]&#39;</span><span class="p">;</span>

<span class="nv">$model</span><span class="o">-&gt;</span><span class="na">setValidationRule</span><span class="p">(</span><span class="nv">$fieldName</span><span class="p">,</span> <span class="nv">$fieldRules</span><span class="p">);</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="setValidationRules">
<code class="descname">setValidationRules</code><span class="sig-paren">(</span><em>$validationRules</em><span class="sig-paren">)</span><a class="headerlink" href="#setValidationRules" title="Permalink to this definition">¶</a></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple">
<li><strong>$validationRules</strong> (<em>array</em>) – </li>
</ul>
</td>
</tr>
</tbody>
</table>
<p>This function will set the validation rules.</p>
<p>Usage example:</p>
<div class="highlight-html+php notranslate"><div class="highlight"><pre><span></span><span class="nv">$validationRules</span> <span class="o">=</span> <span class="p">[</span>
    <span class="s1">&#39;username&#39;</span> <span class="o">=&gt;</span> <span class="s1">&#39;required|alpha_numeric_space|min_length[3]&#39;</span><span class="p">,</span>
    <span class="s1">&#39;email&#39;</span> <span class="o">=&gt;</span> <span class="p">[</span>
        <span class="s1">&#39;rules&#39;</span>  <span class="o">=&gt;</span> <span class="s1">&#39;required|valid_email|is_unique[users.email]&#39;</span><span class="p">,</span>
        <span class="s1">&#39;errors&#39;</span> <span class="o">=&gt;</span> <span class="p">[</span>
            <span class="s1">&#39;required&#39;</span> <span class="o">=&gt;</span> <span class="s1">&#39;We really need your email.&#39;</span><span class="p">,</span>
        <span class="p">],</span>
    <span class="p">],</span>
<span class="p">];</span>
<span class="nv">$model</span><span class="o">-&gt;</span><span class="na">setValidationRules</span><span class="p">(</span><span class="nv">$validationRules</span><span class="p">);</span>
</pre></div>
</div>
</dd></dl>

<p>The other way to set the validation message to fields by functions,</p>
<dl class="function">
<dt id="setValidationMessage">
<code class="descname">setValidationMessage</code><span class="sig-paren">(</span><em>$field</em>, <em>$fieldMessages</em><span class="sig-paren">)</span><a class="headerlink" href="#setValidationMessage" title="Permalink to this definition">¶</a></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple">
<li><strong>$field</strong> (<em>string</em>) – </li>
<li><strong>$fieldMessages</strong> (<em>array</em>) – </li>
</ul>
</td>
</tr>
</tbody>
</table>
<p>This function will set the field wise error messages.</p>
<p>Usage example:</p>
<div class="highlight-html+php notranslate"><div class="highlight"><pre><span></span><span class="nv">$fieldName</span> <span class="o">=</span> <span class="s1">&#39;name&#39;</span><span class="p">;</span>
<span class="nv">$fieldValidationMessage</span> <span class="o">=</span> <span class="p">[</span>
    <span class="s1">&#39;required&#39;</span> <span class="o">=&gt;</span> <span class="s1">&#39;Your name is required here&#39;</span><span class="p">,</span>
<span class="p">];</span>
<span class="nv">$model</span><span class="o">-&gt;</span><span class="na">setValidationMessage</span><span class="p">(</span><span class="nv">$fieldName</span><span class="p">,</span> <span class="nv">$fieldValidationMessage</span><span class="p">);</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="setValidationMessages">
<code class="descname">setValidationMessages</code><span class="sig-paren">(</span><em>$fieldMessages</em><span class="sig-paren">)</span><a class="headerlink" href="#setValidationMessages" title="Permalink to this definition">¶</a></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple">
<li><strong>$fieldMessages</strong> (<em>array</em>) – </li>
</ul>
</td>
</tr>
</tbody>
</table>
<p>This function will set the field messages.</p>
<p>Usage example:</p>
<div class="highlight-html+php notranslate"><div class="highlight"><pre><span></span><span class="nv">$fieldValidationMessage</span> <span class="o">=</span> <span class="p">[</span>
    <span class="s1">&#39;name&#39;</span> <span class="o">=&gt;</span> <span class="p">[</span>
        <span class="s1">&#39;required&#39;</span>   <span class="o">=&gt;</span> <span class="s1">&#39;Your baby name is missing.&#39;</span><span class="p">,</span>
        <span class="s1">&#39;min_length&#39;</span> <span class="o">=&gt;</span> <span class="s1">&#39;Too short, man!&#39;</span><span class="p">,</span>
    <span class="p">],</span>
<span class="p">];</span>
<span class="nv">$model</span><span class="o">-&gt;</span><span class="na">setValidationMessages</span><span class="p">(</span><span class="nv">$fieldValidationMessage</span><span class="p">);</span>
</pre></div>
</div>
</dd></dl>

<p>Now, whenever you call the <code class="docutils literal notranslate"><span class="pre">insert()</span></code>, <code class="docutils literal notranslate"><span class="pre">update()</span></code>, or <code class="docutils literal notranslate"><span class="pre">save()</span></code> methods, the data will be validated. If it fails,
the model will return boolean <strong>false</strong>. You can use the <code class="docutils literal notranslate"><span class="pre">errors()</span></code> method to retrieve the validation errors:</p>
<div class="highlight-html+php notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="p">(</span><span class="nv">$model</span><span class="o">-&gt;</span><span class="na">save</span><span class="p">(</span><span class="nv">$data</span><span class="p">)</span> <span class="o">===</span> <span class="k">false</span><span class="p">)</span>
<span class="p">{</span>
    <span class="k">return</span> <span class="nx">view</span><span class="p">(</span><span class="s1">&#39;updateUser&#39;</span><span class="p">,</span> <span class="p">[</span><span class="s1">&#39;errors&#39;</span> <span class="o">=&gt;</span> <span class="nv">$model</span><span class="o">-&gt;</span><span class="na">errors</span><span class="p">()]);</span>
<span class="p">}</span>
</pre></div>
</div>
<p>This returns an array with the field names and their associated errors that can be used to either show all of the
errors at the top of the form, or to display them individually:</p>
<div class="highlight-html+php notranslate"><div class="highlight"><pre><span></span><span class="o">&lt;?</span><span class="nx">php</span> <span class="k">if</span> <span class="p">(</span><span class="o">!</span> <span class="k">empty</span><span class="p">(</span><span class="nv">$errors</span><span class="p">))</span> <span class="o">:</span> <span class="cp">?&gt;</span>
    <span class="p">&lt;</span><span class="nt">div</span> <span class="na">class</span><span class="o">=</span><span class="s">&quot;alert alert-danger&quot;</span><span class="p">&gt;</span>
    <span class="cp">&lt;?php</span> <span class="k">foreach</span> <span class="p">(</span><span class="nv">$errors</span> <span class="k">as</span> <span class="nv">$field</span> <span class="o">=&gt;</span> <span class="nv">$error</span><span class="p">)</span> <span class="o">:</span> <span class="cp">?&gt;</span>
        <span class="p">&lt;</span><span class="nt">p</span><span class="p">&gt;</span><span class="cp">&lt;?</span><span class="o">=</span> <span class="nv">$error</span> <span class="cp">?&gt;</span><span class="p">&lt;/</span><span class="nt">p</span><span class="p">&gt;</span>
    <span class="cp">&lt;?php</span> <span class="k">endforeach</span> <span class="cp">?&gt;</span>
    <span class="p">&lt;/</span><span class="nt">div</span><span class="p">&gt;</span>
<span class="cp">&lt;?php</span> <span class="k">endif</span> <span class="cp">?&gt;</span>
</pre></div>
</div>
<p>If you’d rather organize your rules and error messages within the Validation configuration file, you can do that
and simply set <code class="docutils literal notranslate"><span class="pre">$validationRules</span></code> to the name of the validation rule group you created:</p>
<div class="highlight-html+php notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">UserModel</span> <span class="k">extends</span> <span class="nx">Model</span>
<span class="p">{</span>
    <span class="k">protected</span> <span class="nv">$validationRules</span> <span class="o">=</span> <span class="s1">&#39;users&#39;</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
</div>
<div class="section" id="retrieving-validation-rules">
<h3><a class="toc-backref" href="#id12">Retrieving Validation Rules</a><a class="headerlink" href="#retrieving-validation-rules" title="Permalink to this headline">¶</a></h3>
<p>You can retrieve a model’s validation rules by accessing its <code class="docutils literal notranslate"><span class="pre">validationRules</span></code>
property:</p>
<div class="highlight-html+php notranslate"><div class="highlight"><pre><span></span><span class="nv">$rules</span> <span class="o">=</span> <span class="nv">$model</span><span class="o">-&gt;</span><span class="na">validationRules</span><span class="p">;</span>
</pre></div>
</div>
<p>You can also retrieve just a subset of those rules by calling the accessor
method directly, with options:</p>
<div class="highlight-html+php notranslate"><div class="highlight"><pre><span></span><span class="nv">$rules</span> <span class="o">=</span> <span class="nv">$model</span><span class="o">-&gt;</span><span class="na">getValidationRules</span><span class="p">(</span><span class="nv">$options</span><span class="p">);</span>
</pre></div>
</div>
<p>The <code class="docutils literal notranslate"><span class="pre">$options</span></code> parameter is an associative array with one element,
whose key is either “except” or “only”, and which has as its
value an array of fieldnames of interest.:</p>
<div class="highlight-html+php notranslate"><div class="highlight"><pre><span></span><span class="c1">// get the rules for all but the &quot;username&quot; field</span>
<span class="nv">$rules</span> <span class="o">=</span> <span class="nv">$model</span><span class="o">-&gt;</span><span class="na">getValidationRules</span><span class="p">([</span><span class="s1">&#39;except&#39;</span> <span class="o">=&gt;</span> <span class="p">[</span><span class="s1">&#39;username&#39;</span><span class="p">]]);</span>
<span class="c1">// get the rules for only the &quot;city&quot; and &quot;state&quot; fields</span>
<span class="nv">$rules</span> <span class="o">=</span> <span class="nv">$model</span><span class="o">-&gt;</span><span class="na">getValidationRules</span><span class="p">([</span><span class="s1">&#39;only&#39;</span> <span class="o">=&gt;</span> <span class="p">[</span><span class="s1">&#39;city&#39;</span><span class="p">,</span> <span class="s1">&#39;state&#39;</span><span class="p">]]);</span>
</pre></div>
</div>
</div>
<div class="section" id="validation-placeholders">
<h3><a class="toc-backref" href="#id13">Validation Placeholders</a><a class="headerlink" href="#validation-placeholders" title="Permalink to this headline">¶</a></h3>
<p>The model provides a simple method to replace parts of your rules based on data that’s being passed into it. This
sounds fairly obscure but can be especially handy with the <code class="docutils literal notranslate"><span class="pre">is_unique</span></code> validation rule. Placeholders are simply
the name of the field (or array key) that was passed in as $data surrounded by curly brackets. It will be
replaced by the <strong>value</strong> of the matched incoming field. An example should clarify this:</p>
<div class="highlight-html+php notranslate"><div class="highlight"><pre><span></span><span class="k">protected</span> <span class="nv">$validationRules</span> <span class="o">=</span> <span class="p">[</span>
    <span class="s1">&#39;email&#39;</span> <span class="o">=&gt;</span> <span class="s1">&#39;required|valid_email|is_unique[users.email,id,{id}]&#39;</span>
<span class="p">];</span>
</pre></div>
</div>
<p>In this set of rules, it states that the email address should be unique in the database, except for the row
that has an id matching the placeholder’s value. Assuming that the form POST data had the following:</p>
<div class="highlight-html+php notranslate"><div class="highlight"><pre><span></span><span class="nv">$_POST</span> <span class="o">=</span> <span class="p">[</span>
    <span class="s1">&#39;id&#39;</span> <span class="o">=&gt;</span> <span class="mi">4</span><span class="p">,</span>
    <span class="s1">&#39;email&#39;</span> <span class="o">=&gt;</span> <span class="s1">&#39;foo@example.com&#39;</span>
<span class="p">];</span>
</pre></div>
</div>
<p>then the <code class="docutils literal notranslate"><span class="pre">{id}</span></code> placeholder would be replaced with the number <strong>4</strong>, giving this revised rule:</p>
<div class="highlight-html+php notranslate"><div class="highlight"><pre><span></span><span class="k">protected</span> <span class="nv">$validationRules</span> <span class="o">=</span> <span class="p">[</span>
    <span class="s1">&#39;email&#39;</span> <span class="o">=&gt;</span> <span class="s1">&#39;required|valid_email|is_unique[users.email,id,4]&#39;</span>
<span class="p">];</span>
</pre></div>
</div>
<p>So it will ignore the row in the database that has <code class="docutils literal notranslate"><span class="pre">id=4</span></code> when it verifies the email is unique.</p>
<p>This can also be used to create more dynamic rules at runtime, as long as you take care that any dynamic
keys passed in don’t conflict with your form data.</p>
</div>
<div class="section" id="protecting-fields">
<h3><a class="toc-backref" href="#id14">Protecting Fields</a><a class="headerlink" href="#protecting-fields" title="Permalink to this headline">¶</a></h3>
<p>To help protect against Mass Assignment Attacks, the Model class <strong>requires</strong> that you list all of the field names
that can be changed during inserts and updates in the <code class="docutils literal notranslate"><span class="pre">$allowedFields</span></code> class property. Any data provided
in addition to these will be removed prior to hitting the database. This is great for ensuring that timestamps,
or primary keys do not get changed.</p>
<div class="highlight-html+php notranslate"><div class="highlight"><pre><span></span><span class="k">protected</span> <span class="nv">$allowedFields</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;name&#39;</span><span class="p">,</span> <span class="s1">&#39;email&#39;</span><span class="p">,</span> <span class="s1">&#39;address&#39;</span><span class="p">];</span>
</pre></div>
</div>
<p>Occasionally, you will find times where you need to be able to change these elements. This is often during
testing, migrations, or seeds. In these cases, you can turn the protection on or off:</p>
<div class="highlight-html+php notranslate"><div class="highlight"><pre><span></span><span class="nv">$model</span><span class="o">-&gt;</span><span class="na">protect</span><span class="p">(</span><span class="k">false</span><span class="p">)</span>
      <span class="o">-&gt;</span><span class="na">insert</span><span class="p">(</span><span class="nv">$data</span><span class="p">)</span>
      <span class="o">-&gt;</span><span class="na">protect</span><span class="p">(</span><span class="k">true</span><span class="p">);</span>
</pre></div>
</div>
</div>
<div class="section" id="working-with-query-builder">
<h3><a class="toc-backref" href="#id15">Working With Query Builder</a><a class="headerlink" href="#working-with-query-builder" title="Permalink to this headline">¶</a></h3>
<p>You can get access to a shared instance of the Query Builder for that model’s database connection any time you
need it:</p>
<div class="highlight-html+php notranslate"><div class="highlight"><pre><span></span><span class="nv">$builder</span> <span class="o">=</span> <span class="nv">$userModel</span><span class="o">-&gt;</span><span class="na">builder</span><span class="p">();</span>
</pre></div>
</div>
<p>This builder is already set up with the model’s $table. If you need access to another table
you can pass it in as a parameter, but be aware that this will not return a shared instance:</p>
<div class="highlight-html+php notranslate"><div class="highlight"><pre><span></span><span class="nv">$groupBuilder</span> <span class="o">=</span> <span class="nv">$userModel</span><span class="o">-&gt;</span><span class="na">builder</span><span class="p">(</span><span class="s1">&#39;groups&#39;</span><span class="p">);</span>
</pre></div>
</div>
<p>You can also use Query Builder methods and the Model’s CRUD methods in the same chained call, allowing for
very elegant use:</p>
<div class="highlight-html+php notranslate"><div class="highlight"><pre><span></span><span class="nv">$users</span> <span class="o">=</span> <span class="nv">$userModel</span><span class="o">-&gt;</span><span class="na">where</span><span class="p">(</span><span class="s1">&#39;status&#39;</span><span class="p">,</span> <span class="s1">&#39;active&#39;</span><span class="p">)</span>
                   <span class="o">-&gt;</span><span class="na">orderBy</span><span class="p">(</span><span class="s1">&#39;last_login&#39;</span><span class="p">,</span> <span class="s1">&#39;asc&#39;</span><span class="p">)</span>
                   <span class="o">-&gt;</span><span class="na">findAll</span><span class="p">();</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>You can also access the model’s database connection seamlessly:</p>
<div class="last highlight-html+php notranslate"><div class="highlight"><pre><span></span><span class="nv">$user_name</span> <span class="o">=</span> <span class="nv">$userModel</span><span class="o">-&gt;</span><span class="na">escape</span><span class="p">(</span><span class="nv">$name</span><span class="p">);</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="runtime-return-type-changes">
<h3><a class="toc-backref" href="#id16">Runtime Return Type Changes</a><a class="headerlink" href="#runtime-return-type-changes" title="Permalink to this headline">¶</a></h3>
<p>You can specify the format that data should be returned as when using the find*() methods as the class property,
$returnType. There may be times that you would like the data back in a different format, though. The Model
provides methods that allow you to do just that.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">These methods only change the return type for the next find*() method call. After that,
it is reset to its default value.</p>
</div>
<p><strong>asArray()</strong></p>
<p>Returns data from the next find*() method as associative arrays:</p>
<div class="highlight-html+php notranslate"><div class="highlight"><pre><span></span><span class="nv">$users</span> <span class="o">=</span> <span class="nv">$userModel</span><span class="o">-&gt;</span><span class="na">asArray</span><span class="p">()</span><span class="o">-&gt;</span><span class="na">where</span><span class="p">(</span><span class="s1">&#39;status&#39;</span><span class="p">,</span> <span class="s1">&#39;active&#39;</span><span class="p">)</span><span class="o">-&gt;</span><span class="na">findAll</span><span class="p">();</span>
</pre></div>
</div>
<p><strong>asObject()</strong></p>
<p>Returns data from the next find*() method as standard objects or custom class intances:</p>
<div class="highlight-html+php notranslate"><div class="highlight"><pre><span></span><span class="c1">// Return as standard objects</span>
<span class="nv">$users</span> <span class="o">=</span> <span class="nv">$userModel</span><span class="o">-&gt;</span><span class="na">asObject</span><span class="p">()</span><span class="o">-&gt;</span><span class="na">where</span><span class="p">(</span><span class="s1">&#39;status&#39;</span><span class="p">,</span> <span class="s1">&#39;active&#39;</span><span class="p">)</span><span class="o">-&gt;</span><span class="na">findAll</span><span class="p">();</span>

<span class="c1">// Return as custom class instances</span>
<span class="nv">$users</span> <span class="o">=</span> <span class="nv">$userModel</span><span class="o">-&gt;</span><span class="na">asObject</span><span class="p">(</span><span class="s1">&#39;User&#39;</span><span class="p">)</span><span class="o">-&gt;</span><span class="na">where</span><span class="p">(</span><span class="s1">&#39;status&#39;</span><span class="p">,</span> <span class="s1">&#39;active&#39;</span><span class="p">)</span><span class="o">-&gt;</span><span class="na">findAll</span><span class="p">();</span>
</pre></div>
</div>
</div>
<div class="section" id="processing-large-amounts-of-data">
<h3><a class="toc-backref" href="#id17">Processing Large Amounts of Data</a><a class="headerlink" href="#processing-large-amounts-of-data" title="Permalink to this headline">¶</a></h3>
<p>Sometimes, you need to process large amounts of data and would run the risk of running out of memory.
To make this simpler, you may use the chunk() method to get smaller chunks of data that you can then
do your work on. The first parameter is the number of rows to retrieve in a single chunk. The second
parameter is a Closure that will be called for each row of data.</p>
<p>This is best used during cronjobs, data exports, or other large tasks.</p>
<div class="highlight-html+php notranslate"><div class="highlight"><pre><span></span><span class="nv">$userModel</span><span class="o">-&gt;</span><span class="na">chunk</span><span class="p">(</span><span class="mi">100</span><span class="p">,</span> <span class="k">function</span> <span class="p">(</span><span class="nv">$data</span><span class="p">)</span>
<span class="p">{</span>
    <span class="c1">// do something.</span>
    <span class="c1">// $data is a single row of data.</span>
<span class="p">});</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="model-events">
<h2><a class="toc-backref" href="#id18">Model Events</a><a class="headerlink" href="#model-events" title="Permalink to this headline">¶</a></h2>
<p>There are several points within the model’s execution that you can specify multiple callback methods to run.
These methods can be used to normalize data, hash passwords, save related entities, and much more. The following
points in the model’s execution can be affected, each through a class property: <strong>$beforeInsert</strong>, <strong>$afterInsert</strong>,
<strong>$beforeUpdate</strong>, <strong>$afterUpdate</strong>, <strong>$afterFind</strong>, and <strong>$afterDelete</strong>.</p>
<div class="section" id="defining-callbacks">
<h3><a class="toc-backref" href="#id19">Defining Callbacks</a><a class="headerlink" href="#defining-callbacks" title="Permalink to this headline">¶</a></h3>
<p>You specify the callbacks by first creating a new class method in your model to use. This class will always
receive a $data array as its only parameter. The exact contents of the $data array will vary between events, but
will always contain a key named <strong>data</strong> that contains the primary data passed to the original method. In the case
of the insert* or update* methods, that will be the key/value pairs that are being inserted into the database. The
main array will also contain the other values passed to the method, and be detailed later. The callback method
must return the original $data array so other callbacks have the full information.</p>
<div class="highlight-html+php notranslate"><div class="highlight"><pre><span></span><span class="k">protected</span> <span class="k">function</span> <span class="nf">hashPassword</span><span class="p">(</span><span class="k">array</span> <span class="nv">$data</span><span class="p">)</span>
<span class="p">{</span>
    <span class="k">if</span> <span class="p">(</span><span class="o">!</span> <span class="nb">isset</span><span class="p">(</span><span class="nv">$data</span><span class="p">[</span><span class="s1">&#39;data&#39;</span><span class="p">][</span><span class="s1">&#39;password&#39;</span><span class="p">])</span> <span class="k">return</span> <span class="nv">$data</span><span class="p">;</span>

    <span class="nv">$data</span><span class="p">[</span><span class="s1">&#39;data&#39;</span><span class="p">][</span><span class="s1">&#39;password_hash&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="nb">password_hash</span><span class="p">(</span><span class="nv">$data</span><span class="p">[</span><span class="s1">&#39;data&#39;</span><span class="p">][</span><span class="s1">&#39;password&#39;</span><span class="p">],</span> <span class="nx">PASSWORD_DEFAULT</span><span class="p">);</span>
    <span class="nb">unset</span><span class="p">(</span><span class="nv">$data</span><span class="p">[</span><span class="s1">&#39;data&#39;</span><span class="p">][</span><span class="s1">&#39;password&#39;</span><span class="p">];</span>

    <span class="k">return</span> <span class="nv">$data</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
</div>
<div class="section" id="specifying-callbacks-to-run">
<h3><a class="toc-backref" href="#id20">Specifying Callbacks To Run</a><a class="headerlink" href="#specifying-callbacks-to-run" title="Permalink to this headline">¶</a></h3>
<p>You specify when to run the callbacks by adding the method name to the appropriate class property (beforeInsert, afterUpdate,
etc). Multiple callbacks can be added to a single event and they will be processed one after the other. You can
use the same callback in multiple events:</p>
<div class="highlight-html+php notranslate"><div class="highlight"><pre><span></span><span class="k">protected</span> <span class="nv">$beforeInsert</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;hashPassword&#39;</span><span class="p">];</span>
<span class="k">protected</span> <span class="nv">$beforeUpdate</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;hashPassword&#39;</span><span class="p">];</span>
</pre></div>
</div>
<p>Additionally, each model may allow (default) or deny callbacks class-wide by setting its $allowCallbacks property:</p>
<div class="highlight-html+php notranslate"><div class="highlight"><pre><span></span><span class="k">protected</span> <span class="nv">$allowCallbacks</span> <span class="o">=</span> <span class="k">false</span><span class="p">;</span>
</pre></div>
</div>
<p>You may also change this setting temporarily for a single model call sing the <code class="docutils literal notranslate"><span class="pre">allowCallbacks()</span></code> method:</p>
<div class="highlight-html+php notranslate"><div class="highlight"><pre><span></span><span class="nv">$model</span><span class="o">-&gt;</span><span class="na">allowCallbacks</span><span class="p">(</span><span class="k">false</span><span class="p">)</span><span class="o">-&gt;</span><span class="na">find</span><span class="p">(</span><span class="mi">1</span><span class="p">);</span> <span class="c1">// No callbacks triggered</span>
<span class="nv">$model</span><span class="o">-&gt;</span><span class="na">find</span><span class="p">(</span><span class="mi">1</span><span class="p">);</span>                        <span class="c1">// Callbacks subject to original property value</span>
</pre></div>
</div>
</div>
<div class="section" id="event-parameters">
<h3><a class="toc-backref" href="#id21">Event Parameters</a><a class="headerlink" href="#event-parameters" title="Permalink to this headline">¶</a></h3>
<p>Since the exact data passed to each callback varies a bit, here are the details on what is in the $data parameter
passed to each event:</p>
<table border="1" class="docutils">
<colgroup>
<col width="13%" />
<col width="87%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Event</th>
<th class="head">$data contents</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>beforeInsert</td>
<td><strong>data</strong> = the key/value pairs that are being inserted. If an object or Entity class is passed to the
insert method, it is first converted to an array.</td>
</tr>
<tr class="row-odd"><td>afterInsert</td>
<td><strong>id</strong> = the primary key of the new row, or 0 on failure.
<strong>data</strong> = the key/value pairs being inserted.
<strong>result</strong> = the results of the insert() method used through the Query Builder.</td>
</tr>
<tr class="row-even"><td>beforeUpdate</td>
<td><strong>id</strong> = the array of primary keys of the rows being updated.
<strong>data</strong> = the key/value pairs that are being inserted. If an object or Entity class is passed to the
insert method, it is first converted to an array.</td>
</tr>
<tr class="row-odd"><td>afterUpdate</td>
<td><strong>id</strong> = the array of primary keys of the rows being updated.
<strong>data</strong> = the key/value pairs being updated.
<strong>result</strong> = the results of the update() method used through the Query Builder.</td>
</tr>
<tr class="row-even"><td>beforeFind</td>
<td>The name of the calling <strong>method</strong>, whether a <strong>singleton</strong> was requested, and these additional fields:</td>
</tr>
<tr class="row-odd"><td><ul class="first last simple">
<li>first()</li>
</ul>
</td>
<td>No additional fields</td>
</tr>
<tr class="row-even"><td><ul class="first last simple">
<li>find()</li>
</ul>
</td>
<td><strong>id</strong> = the primary key of the row being searched for.</td>
</tr>
<tr class="row-odd"><td><ul class="first last simple">
<li>findAll()</li>
</ul>
</td>
<td><strong>limit</strong> = the number of rows to find.
<strong>offset</strong> = the number of rows to skip during the search.</td>
</tr>
<tr class="row-even"><td>afterFind</td>
<td>Same as <strong>beforeFind</strong> but including the resulting row(s) of data, or null if no result found.</td>
</tr>
<tr class="row-odd"><td>beforeDelete</td>
<td>Varies by delete* method. See the following:</td>
</tr>
<tr class="row-even"><td><ul class="first last simple">
<li>delete()</li>
</ul>
</td>
<td><strong>id</strong> = primary key of row being deleted.
<strong>purge</strong> = boolean whether soft-delete rows should be hard deleted.</td>
</tr>
<tr class="row-odd"><td>afterDelete</td>
<td><strong>id</strong> = primary key of row being deleted.
<strong>purge</strong> = boolean whether soft-delete rows should be hard deleted.
<strong>result</strong> = the result of the delete() call on the Query Builder.
<strong>data</strong> = unused.</td>
</tr>
</tbody>
</table>
</div>
<div class="section" id="modifying-find-data">
<h3><a class="toc-backref" href="#id22">Modifying Find* Data</a><a class="headerlink" href="#modifying-find-data" title="Permalink to this headline">¶</a></h3>
<p>The <code class="docutils literal notranslate"><span class="pre">beforeFind</span></code> and <code class="docutils literal notranslate"><span class="pre">afterFind</span></code> methods can both return a modified set of data to override the normal response
from the model. For <code class="docutils literal notranslate"><span class="pre">afterFind</span></code> any changes made to <code class="docutils literal notranslate"><span class="pre">data</span></code> in the return array will automatically be passed back
to the calling context. In order for <code class="docutils literal notranslate"><span class="pre">beforeFind</span></code> to intercept the find workflow it must also return an additional
boolean, <code class="docutils literal notranslate"><span class="pre">returnData</span></code>:</p>
<div class="highlight-html+php notranslate"><div class="highlight"><pre><span></span><span class="k">protected</span> <span class="nv">$beforeFind</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;checkCache&#39;</span><span class="p">];</span>
<span class="c1">// ...</span>
<span class="k">protected</span> <span class="k">function</span> <span class="nf">checkCache</span><span class="p">(</span><span class="k">array</span> <span class="nv">$data</span><span class="p">)</span>
<span class="p">{</span>
    <span class="c1">// Check if the requested item is already in our cache</span>
    <span class="k">if</span> <span class="p">(</span><span class="nb">isset</span><span class="p">(</span><span class="nv">$data</span><span class="p">[</span><span class="s1">&#39;id&#39;</span><span class="p">])</span> <span class="o">&amp;&amp;</span> <span class="nv">$item</span> <span class="o">=</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">getCachedItem</span><span class="p">(</span><span class="nv">$data</span><span class="p">[</span><span class="s1">&#39;id&#39;</span><span class="p">]]))</span>
    <span class="p">{</span>
        <span class="nv">$data</span><span class="p">[</span><span class="s1">&#39;data&#39;</span><span class="p">]</span>       <span class="o">=</span> <span class="nv">$item</span><span class="p">;</span>
        <span class="nv">$data</span><span class="p">[</span><span class="s1">&#39;returnData&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="k">true</span><span class="p">;</span>

        <span class="k">return</span> <span class="nv">$data</span><span class="p">;</span>
<span class="c1">// ...</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="manual-model-creation">
<h2><a class="toc-backref" href="#id23">Manual Model Creation</a><a class="headerlink" href="#manual-model-creation" title="Permalink to this headline">¶</a></h2>
<p>You do not need to extend any special class to create a model for your application. All you need is to get an
instance of the database connection and you’re good to go. This allows you to bypass the features CodeIgniter’s
Model gives you out of the box, and create a fully custom experience.</p>
<div class="highlight-html+php notranslate"><div class="highlight"><pre><span></span><span class="o">&lt;?</span><span class="nx">php</span>

<span class="k">namespace</span> <span class="nx">App\Models</span><span class="p">;</span>

<span class="k">use</span> <span class="nx">CodeIgniter\Database\ConnectionInterface</span><span class="p">;</span>

<span class="k">class</span> <span class="nc">UserModel</span>
<span class="p">{</span>
    <span class="k">protected</span> <span class="nv">$db</span><span class="p">;</span>

    <span class="k">public</span> <span class="k">function</span> <span class="fm">__construct</span><span class="p">(</span><span class="nx">ConnectionInterface</span> <span class="o">&amp;</span><span class="nv">$db</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">db</span> <span class="o">=</span> <span class="o">&amp;</span><span class="nv">$db</span><span class="p">;</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
</div>
</div>


           </div>
           
          </div>
          <footer>
    <div class="rst-footer-buttons" role="navigation" aria-label="footer navigation">
        <a href="entities.html" class="btn btn-neutral float-right" title="Using Entity Classes" accesskey="n" rel="next">Next <span class="fa fa-arrow-circle-right" aria-hidden="true"></span></a>
        <a href="index.html" class="btn btn-neutral float-left" title="Modeling Data" accesskey="p" rel="prev"><span class="fa fa-arrow-circle-left" aria-hidden="true"></span> Previous</a>
    </div>

  <hr/>

  <div role="contentinfo">
    <p>
        &#169; Copyright 2019-2021 CodeIgniter Foundation.
      <span class="lastupdated">
        Last updated on Feb 01, 2021.
      </span>

    </p>
  </div>
    
    
    
    Built with <a href="https://www.sphinx-doc.org/">Sphinx</a> using a
    
    <a href="https://github.com/readthedocs/sphinx_rtd_theme">theme</a>
    
    provided by <a href="https://readthedocs.org">Read the Docs</a>. 

</footer>
        </div>
      </div>

    </section>

  </div>
  

  <script type="text/javascript">
      jQuery(function () {
          SphinxRtdTheme.Navigation.enable(false);
      });
  </script>

  
  
    
   

</body>
</html>