Welcome Guest, Not a member yet? Register   Sign In
What's the best approach to access related data in CodeIgniter 4?
#1

As a beginner in CodeIgniter 4 and MVC, I am struggling to design a Model that includes information from two tables - Projects and Hours. I have created a basic Project Model, but I want to include hours associated with each project. I have set up my database using Primary and Foreign Keys, but I am unsure of the best approach to access the hours information.

Should I create a separate Hours Model or add a method to my Project Model that queries the Hours table? What is the recommended best practice for this situation?
Reply
#2

It depends on your use case. There is no best practice.
Reply
#3

(04-19-2023, 10:40 PM)GerishSonya Wrote: As a beginner in CodeIgniter 4 and MVC, I am struggling to design a Model that includes information from two tables - Projects and Hours. I have created a basic Project Model, but I want to include hours associated with each project. I have set up my database using Primary and Foreign Keys, but I am unsure of the best approach to access the hours information.

Should I create a separate Hours Model or add a method to my Project Model that queries the Hours table? What is the recommended best practice for this situation?

If your intent is to merely represent the relationship, separate models would be better for maintaining the code. If your intent is to always represent Projects and related Hours as a single entity, you could use a single model. However, since the Codeigniter model is optimized to represent a single table, you might end up doing a lot of extra work to maintain the related table.

Using separate models, you can always write class methods in the Projects model to retrieve records from the Hours table through the Hours model.

You can also use entity class methods to calculate Project totals, retrieve the last Hours record, etc.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB