Welcome Guest, Not a member yet? Register   Sign In
Model within a model
#9

(This post was last modified: 07-01-2021, 12:43 AM by paulkd. Edit Reason: add function for better clarity of purpose )

Hi, In general, I call models from controllers. However, here is an example where I've called Customers model from Orders model. Hope this helps.

Models/BaseModel.php
PHP Code:
<?php

namespace App\Models;

use 
CodeIgniter\Model;

class 
BaseModel extends Model
{
  protected $db;

  protected function __construct()
  {
    $this->db = \Config\Database::connect();
  

Models/Customers.php
PHP Code:
<?php

namespace App\Models;

use 
App\Models\BaseModel;

class 
Customers extends BaseModel
{
  protected $fields;

  public function __construct()
  {
    parent::__construct();
  }

  public function getCustomer(int $customerId)
  {
    $builder $this->db->table('customers c');
    $query $builder->select($this->fields['customers-all'])->where('c.id'$customerId)->get();
    return $query->getRowArray();
  

Models/Orders.php
PHP Code:
<?php

namespace App\Models;

use 
App\Models\BaseModel;

class 
Orders extends BaseModel
{
  protected $orderTable;
  protected $selectFields;

  public function __construct()
  {
    parent::__construct();
  }

  public function getOrder(int $orderId)
  {
    $c = new \App\Models\Customers;

    $query $this->orderTable->select($this->selectFields['all'])->where('o.id'$orderId)->get();

    $order $query->getRowArray();
    if (!$order) {
      return ['order' => $order];
    }

    $orderItems $this->getOrderItems($orderId);
    $customer $c->getCustomer($order['customer_id']);
    $address $c->getAddress($order['address_id']); 
Reply


Messages In This Thread
Model within a model - by LuxesR - 06-29-2021, 12:31 PM
RE: Model within a model - by BilltheCat - 06-29-2021, 12:52 PM
RE: Model within a model - by LuxesR - 06-29-2021, 01:47 PM
RE: Model within a model - by BilltheCat - 06-29-2021, 02:06 PM
RE: Model within a model - by paulbalandan - 06-30-2021, 12:54 AM
RE: Model within a model - by InsiteFX - 06-30-2021, 01:58 AM
RE: Model within a model - by LuxesR - 06-30-2021, 02:49 AM
RE: Model within a model - by paulbalandan - 06-30-2021, 07:07 PM
RE: Model within a model - by LuxesR - 07-01-2021, 02:58 AM
RE: Model within a model - by paulkd - 07-01-2021, 12:36 AM
RE: Model within a model - by ikesela - 07-01-2021, 02:59 AM
RE: Model within a model - by paulbalandan - 07-01-2021, 04:25 AM
RE: Model within a model - by LuxesR - 07-01-2021, 05:02 AM



Theme © iAndrew 2016 - Forum software by © MyBB