CodeIgniter Forums
Model with joined tables - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forumdisplay.php?fid=30)
+--- Thread: Model with joined tables (/showthread.php?tid=85229)



Model with joined tables - Mni.day - 12-06-2022

Hi
How should I work with model data that is stored in several tables as intended by the framework?
Should I override the save method in the main Model and write data in my code?
Or should I create additional models for all related tables? With this approach, should I save / read nested models by overriding the save method or work with them separately from the controller?


RE: Model with joined tables - InsiteFX - 12-08-2022

For your problem I would use CodeIgniter 4 Standard Query.

CodeIgniter 4 User Guide - Database Quick Start: Example Code


RE: Model with joined tables - Mni.day - 12-08-2022

But.. 90% of cases the data are distributed on several tables:
A user can have several avatars, which are stored in a separate table.
The service can have several tariff plans.
Article - multiple authors...

The model does not have the ability to work with nested (related) models or tables?
I can not use models for it?

I view the Model as a Repository


RE: Model with joined tables - [email protected] - 12-12-2022

Maybe u can add callbacks on model to update/insert related data on other tables like on afterInsert and afterUpdate event.


RE: Model with joined tables - Mni.day - 12-15-2022

Maybe. What a best practice for this cases?


RE: Model with joined tables - groovebird - 12-15-2022

What are nested models?

Why not creating additional models? Then you can use the save method for every model. Unfortunately CI has no option for using relations in models.


RE: Model with joined tables - Mni.day - 12-15-2022

I have a userModel

Code:
[users]
user_id | name | ...


Every user have same avatar images

Code:
[avatars]
avatar_id | user_is | uri | is_dafault | ...


When I got User entity from userModel I wanna access to

PHP Code:
$User->avatars($only_default false); // return plain array or array of entities of Avatar() 


Yes, I can load avatars directly in method. But what if i need build a table of users with avatars?
I would not like to make 50 requests in a cycle.
How to do it right?
Given that I still need a list of social networks and etc

Maybe something that


PHP Code:
$Users $userModel->withAvatars()->get([1,2,3]);
$Users $userModel->withAvatars()->withSocials()->get([1,2,3]); 

Or only this way?

PHP Code:
$Users $userModel->get(...);
$Avatars $avatarModel->get(...);
foreach(
$Avatars AS $Avatar){
   $Users{$Avatar->user_id][] = $Avatar;




(sorry for my english)