Welcome Guest, Not a member yet? Register   Sign In
Can I have 2 tables in codeigniter 4 model?
#2

I've never used CI3, but I have been able to accomplish what you describe in CI4 by using the standard CI4 model and Entities.  Create a method inside your model that joins other tables with your model's table. Then the query's results can be returned as an Entity object by the method where the attributes of that Entity are columns from all of the joined tables.

First create your Entity: https://codeigniter.com/user_guide/models/entities.html.

Then, configure the model to return an Entity object instead of the usual array.

PHP Code:
protected $returnType    'App\Entities\User'

Create a method that joins multiple tables together in your model.

PHP Code:
public function byUserID(string $user_id) {
    $user = $this
        
->join('user_roles', 'users.role_id = user_roles.role_id')
        ->join('job_list', 'users.job_id = job_list.job_id')
        ->where('user_id', $user_id)
        ->first();
    return $user;


In this case, a User entity object is returned where the database columns for all joined tables are attributes.

PHP Code:
$user_model = new \App\Models\UserModel//Instantiate model
$user $user_model->byUserID('12345678'); //Instantiate User entity

echo $user->username;         //From users table
echo $user->first_name;       //From users table
echo $user->last_name;        //From users table
echo $user->role_name;        //From user_roles table
echo $user->job_name;         //From job_list table
echo $user->job_description;  //From job_list table 

You can also create new methods in your entity to add attributes.

PHP Code:
public function getFullName() {
    $this->attributes['full_name'] = $this->attributes['first_name'] . ' ' . $this->attributes['last_name'];
    return $this->attributes['full_name'];


$user->full_name will automatically call $user->getFullName() and return the result. For this to work properly your method name must begin with "get" and use camel case.  CI4 automatically converts the camel case method name to a snake case attribute. (e.g. $entity->getMethodName() translates to $entity->method_name)

I hope this helps!  Let me know how you make out.
Reply


Messages In This Thread
RE: Can I have 2 tables in codeigniter 4 model? - by mlurie - 10-28-2020, 06:46 PM



Theme © iAndrew 2016 - Forum software by © MyBB