Dr3am3rz
Dr3am3rz

Reputation: 563

Codeigniter 4 multiple database tables in 1 model file

I have 1 database and inside there are maybe say 3 tables, users, user_profile, user_stats. I would like to ask is it possible to have these 3 tables in 1 model file? If user were to visit User A profile, it will show all the User A records from these 3 tables. I can't find it anywhere whether is it possible in CI4. Hope someone here can guide me on this. Thanks in advance guys!

Upvotes: 0

Views: 1735

Answers (1)

Dhaval Chheda
Dhaval Chheda

Reputation: 924

You will need to override the find method. I have done it for findAll and haven't tried for find a method. So you may need to improvise on the following logic. There are three places where based on the condition we are fetching the rows, one check for the array, another for a single row, and last is the default one. So you will need to modify this behavior.

Replace : $row = $builder

With your custom builder query such as following:

 $row = $builder->select("users.*");
$builder->join('user_profile', 'user_profile.id = users.id','inner');
$builder->join('user_stats', 'user_stats.id = users.id','inner');
->whereIn($this->table . '.' . $this->primaryKey, $id)
->get();

You will need to replace the last query according to the conditions in find method and also instead of mentioning users explicitly you should use $this->table and similar for the primary key instead of id, you should use $this->primaryKey.

Upvotes: 1

Related Questions