Welcome Guest, Not a member yet? Register   Sign In
Model best practices question
#1

(This post was last modified: 07-20-2024, 04:10 PM by wolverine4277.)

I'm building a REST API with four endpoints (I must say that I just started with CodeIgniter). One of them is to get data, and it receives two parameters id, and code via GET.
The issue is that the data is fetched from five different tables, all related (say table1, table2, ..., table5).
Here I have a doubt about what is the right way to build the solution:
Option 1: Create a model where I get the information from a SQL that joins all tables filtering on table1 where: (table1.id = id) AND (table1.code = code) AND (table1.status <> 'REJECTED') and have the controller call this model method. For example, in the controller I would have a method that contains something similar to the following:


PHP Code:
$dataModel = new DataModel();

// Retrieve data from all the tables with one SQL and JOINS
$data $dataModel->getData($id$code);

$responseData = [
    'column1' => data['column1'],
    'column2' => data['column2'],
    'column3' => data['column4'],
    ...
    'columnN' => data['columN']
]; 
Option 2: Create multiple models, one per table and from the controller call the methods that return me the information of each model. For example, in the controller I would have a method that contains something similar to the following:


PHP Code:
$table1Model = new Table1Model();
$table2Model = new Table2Model();
$table3Model = new Table3Model();
$table4Model = new Table4Model();
$table5Model = new Table5Model();

// Retrieve data from table1 table
$table1Data $table1Model->getData($id$code);

// Retrieve data from table2 table table1.idTable2 = table2.id
$table2Data $table2Model->getData($idTable2);

// Retrieve data from table3 table table table1.id = table3.idTable1
$table3Data $table3Model->getData($id);

// Retrieve data from table4 table table table2.id = table4.idTable2
$table4Data $table4Model->getData($idTable2);

// Retrieve data from table5 table table1.idTable5 = table5.id
$table5Data $table5Model->getData($idTable5);

$responseData = [
    'column1' => table1Data['table1Column1'],
    'column2' => table2Data['table2Column2'],
    'column3' => table3Data['table3Column4'],
    ...
    'columnN' => table5Data['table5ColumN']
]; 

The same query would be for an endpoint that needs to insert or update data in multiple tables.
What would be the best option? Is there a better one that I don't realize?

Any opinion/help is welcome!
Regards.
Reply


Messages In This Thread
Model best practices question - by wolverine4277 - 07-20-2024, 03:13 PM
RE: Model best practices question - by demyr - 07-22-2024, 04:05 AM
RE: Model best practices question - by ozornick - 07-22-2024, 08:59 AM



Theme © iAndrew 2016 - Forum software by © MyBB