Get data from multiple codeigniter tables (Multidimensional Array)?

Asked

Viewed 681 times

1

How to get data from multiple tables at once?

I need to recover the data of the following object (debtor).

There are several tables where the main table is tbl_devedor. After that, there are others, which are related to tbl_devedor.

Example:

  • tbl_devedor
  • tbl_email
  • id_contrato
  • id_telefone
  • id_endereco

inserir a descrição da imagem aqui

Follows below the array

$dados = array(
    'contratos' => [],
    'id' => '',
    'id_operador' => 0,
    'pessoa_fisica' => array(
          'id' => 0,
          'rg' => '',
          'dt_nascimento' => '',
          'profissao' => '',
          'salario' => '',
          'genero' => '',
        ),
    'pessoa_juridica' => array (
         'id' => 0,
         'nome_fantasia' => '',
         'inscricao_estadual' => ''
    ),
    'nome' => '',
    'cpf_cnpj' => '',
    'emails' => [],
    'enderecos' => [],
    'telefones' => [],
    'crud' => null
);

echo json_encode($dados);

Remembering that contratos, pessoa_fisicao, pessoa_juridica, emails, enderecos, telefones, comes from different tables, so far what I have is this:

Controller

$devedor = $this->devedor->obter_por_id($id);

Model

public function obter_por_id($id)
{
    $this->db->from($this->tbl_devedor);
    $this->db->where('id',$id);
    $query = $this->db->get();
    return $query->row();
}

I know how to do the Join and get the data from the other tables, but I don’t know how the structure of array.

  • Wagner you need to put in your question the bank diagram with these tables.

  • 1

    Okay! Done that.

1 answer

2


Even the information being related, I’d make a class Model for each table and then a class Model to manage the others as follows:

Minimal Example:

Observing: in this simple example were placed two of these tables the others follow the same layout programming and the proposed idea.

class Devedor_model

<?php

    class Devedor_model extends CI_Model 
    {

        public function obter_por_id($id)
        {
            $this->db->from('tbl_devedor');
            $this->db->where('id',$id);
            $query = $this->db->get();
            return $query->row_array();
        }

    }

class Devedoremail_model

<?php

    class Devedoremail_model extends CI_Model 
    {   

        public function obter_por_id_email($id)
        {
            $this->db->from('tbl_devedor_email');
            $this->db->where('devedor_id',$id);
            $query = $this->db->get();
            return $query->result_array();
        }

    }

these two classes Model would now be used in another class Model that would manage and manipulate this data at once and will generate the array expected:

<?php

    class Devedordados_model extends CI_Model 
    {
        private $CI;

        public function __construct()
        {
            parent::__construct();
            $this->CI =& get_instance();
            // subindo as classe model coloque todas
            $this->CI->load->model("devedor_model");
            $this->CI->load->model("devedoremail_model");
        }

        public function obter_todos_dados_por_id($id)
        {
            $result = array();
            $result = $this->devedor_model->obter_por_id($id);
            $result['email'] = $this->devedoremail_model->obter_por_id_email($id);
            // insere aqui os outros models 
            //$result['enderecos'] = 
            //$result['telefones'] = 
            return $result;
        }

    }

and finally in the controller is called the class that manages all the Model, Devedordados_model:

public function de()
{
    $id = 1;
    $this->load->model('Devedordados_model');

    echo json_encode($this->Devedordados_model->obter_todos_dados_por_id($id),
                     JSON_PRETTY_PRINT);

}

the result obtained by that method of Controller:

{
    "id": "1",
    "nome": "Devedor 1",
    "email": [
        {
            "id": "1",
            "email": "[email protected]",
            "devedor_id": "1"
        },
        {
            "id": "2",
            "email": "[email protected]",
            "devedor_id": "1"
        }
    ]
}

and that would be a proposal, upon your doubt

References:

  • 1

    It worked out this way, thank you..

  • only one other doubt, in this part public function obter_por_id_email($id)&#xA; {&#xA; $this->db->from('tbl_devedor_email');&#xA; $this->db->where('devedor_id',$id);&#xA; $query = $this->db->get();&#xA; return $query->result_array();&#xA; } i can change a field individually, before returning it to the debtor object ?

  • I tried like this and it didn’t work: foreach ($query->result_array() as $row)

  • Cara is very specific that you may not need to go through an array maybe an alias already solves, but, tell me in full what you need to do @Wagnerfilho

  • Because when I get by id, obter_por_id_email I take all fields and display exactly what is in the database. These are the table fields tbl_devedor_email, 'id', 'email', 'crud', 'devedor_id', 'id_origem_dados', 'observacao', 'preferencial', 'situacao' If possible, the field crud has a result equal to C, the object recovers crud: C. I want to change this field to crud: R.

  • Look I do not understand your doubt is confused Crud C Crud R did not even understand .... @Wagnerson only says what is to be done, just one thing, this is a new doubt if by venturar want to open a new!

  • The purpose of the question was to recover the data in general; as for that OK, it is working.. Now when retrieving the data from the email table, for example, I want to change the result of one of the fields, in this case the field crud.

  • The field crud which is part of tbl_devedor, you want to show another value in the result, or/and also change the value that is saved in the base by saving the new value? @Wagnerfilho

  • Only show another value in the result. Because when this value is recovered by json, the system will understand, that the method to be used is R.

  • See this image: https://ibb.co/fSHwU5

  • Can you help me again ? email. this field will be called, view and is view should recover data from another table. How can I do this? : view: {id: "1", nome: "admin":}

  • If you could open another question @Wagnerfilho by attaching this as a primary answer?

  • Open question: https://answall.com/questions/235596/obtains-array-multidimensional-codeigniter?noredirect=1#comment482290_235596

Show 9 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.