首页 > 解决方案 > 使用 CodeIgniter 4 从数据库中列出用户

问题描述

我是 CodeIgniter 4 的新手,我需要显示一个用户列表,其中包含来自多个表的用户详细信息:users、users_details、user_contact_details、company、company_positions、departments。在表 users_details 中,我有公司、公司职位和部门的外键。

我真的需要你的支持。

这是我的代码。

谢谢!

模型 User_Model.php

namespace App\Models;
use CodeIgniter\Model;

class User_Model extends Model {
    
    
    public function get_user()
    {
        return $this->db->table('users')
        ->join('users_details','users_details.user_id_fk = users.user_id')     
        ->join('user_contact_details','user_contact_details.user_id_fk = users.user_id')      
        ->get()->getResultArray();
    }
    
        public function get_user_company_details()
    {
        return $this->db->table('users_details')
        ->join('company','company.company_id = users_details.company_id_fk')          
        ->join('company_positions','company_positions.position_id = users_details.position_id_fk')
        ->join('departments','departments.department_id = users_details.department_id_fk')        
        ->get()->getResultArray();
    }
   
}

控制器用户.php

namespace App\Controllers;
use CodeIgniter\Controller;
use App\Models\User_Model;

class Users extends BaseController
{     
    protected $User_Model;
        
        public function __construct()
        {
            $this->User_Model = new User_Model();
        }
        
        public function list_users()
        {
            $data=[
                'user' =>$this->User_Model->get_user(),
            ];
            
         foreach ($data['user'] as $type) {
            
            $type = [
                'company' => $this->User_Model->get_user_company_details(),
                ];
     }
            echo view('users/list_users', $data);
        }

}

查看 list_users.php

<table id="useful_links" class="table table-striped projects" role="grid" aria-describedby="example2_info">
   <thead>
      <tr>
         <td>Id</td>
         <td>Name</td>
         <td>Phone</td>
         <td>E-mail</td>
         <td>Vacation days</td>   
         <td>Position</td>  
         <td>Active</td>
         <td>Deleted</td>
         <td>Options</td>
      </tr>
   </thead>
   <?php
      $n=1;
      foreach ($user as $row)
      {?>
   <tr>
      <td><?php echo $n;?>
      <td><div class="user-block">
              <span class="username" style="margin-top:5px;"><?php echo $row['surname']." ".$row['firstname'];?> </span></div></td>
      <td><?php echo $row['user_phone'];?></td>
      <td><?php echo $row['user_email'];?></td>
      <td><?php echo $row['yearly_vacation_days'];?></td>
      <td>
          <?php  foreach ($company as $row)
      {
              echo $row['position_name'];
      }?>
      </td>
      <td><?php echo $row['user_active'];?></td>
      <td><?php echo $row['user_deleted'];?></td>
      <td>
         <a href="<?php echo site_url('/useful_links/editUseful_link/'.$row['link_id']);?>" class="btn btn-primary btn-sm" href="#"><i class="fas fa-folder"></i> View</a>&nbsp;
         <a href="<?php echo site_url('/useful_links/editUseful_link/'.$row['link_id']);?>" class="btn btn-info btn-sm"><i class="fas fa-pencil-alt"></i> Edit</a>&nbsp;
         <a href="<?php echo site_url('/useful_links/delete/'.$row['link_id']);?>" class="btn btn-danger btn-sm"><i class="fas fa-trash"></i> Delete</a>
      </td>
      <?php $n++;   }
         ?>
</table>

标签: phpcodeigniter-4

解决方案


在您的情况下,您需要使用的是模型回调。

首先,您的模型应该有更多信息才能使用此功能,如下所示:

<?php namespace App\Models;
use CodeIgniter\Model;

class User_Model extends Model {
    
    protected $table      = 'users';
    protected $primaryKey = 'id';
    protected $returnType     = 'array';
    protected $allowedFields = ['name', 'email']; // You should expand this to the exact fields you're updating and editing
    protected $afterFind = ['userCompanyDetails'];

    /**
        Now since this is a afterFind callback there's a find things 
        you'll have to consider, since your $user will vary depending 
        on how you call this model

        $user->find()

        id = the primary key of the row being searched for.
        data = The resulting row of data, or null if no result found.

        $user->findAll()

        data = the resulting rows of data, or null if no result found.
        limit = the number of rows to find.
        offset = the number of rows to skip during the search.

        $user->first()

        data = the resulting row found during the search, or null if none found.
    */
    protected function userCompanyDetails($user) {
        $db      = \Config\Database::connect();
        $builder = $db->table('users_details');
        
        if(isset($user['id']) {
           $user['data']['user_details'] = $builder->join('users_details','users_details.user_id_fk = users.user_id')     
    ->join('user_contact_details','user_contact_details.user_id_fk = users.user_id')
    ->where('user_details.user_id_fk', $user['data']['id'])     
    ->get()->getResultArray();
        } else {
        
             foreach($user['data'] as $key => $u){
                 $user['data'][$key]['user_details'] = $builder->join('users_details','users_details.user_id_fk = users.user_id')     
                 ->join('user_contact_details','user_contact_details.user_id_fk = users.user_id')
                 ->where('user_details.user_id_fk', $user['data']['id'])     
                 ->get()->getResultArray();
             }
        }

        return $user;
    }
   
}

您可以拥有任意数量的事件,并且他们可以根据用户信息进行自己的查询。

至于你的控制器,我也会改变一些东西,首先你不应该在 CI4 控制器中使用构造魔法方法。相反,您应该使用基本控制器中描述的 init 方法。

namespace App\Controllers;
use CodeIgniter\Controller;
use App\Models\User_Model;

class Users extends BaseController
{     
        protected $User_Model;
        
        public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
        {
            $this->UserModel = new User_Model();
        }
        
        public function list_users()
        {
            $data['user'] = $this->User_Model->findAll();
            return view('users/list_users', $data);
        }

}

这样,您只需使用 CodeIgniter 模型中的 findAll 函数并将其添加到您的数据中。

有关模型事件的更多信息,您可以在此处阅读:https ://codeigniter.com/user_guide/models/model.html#model-events

或者,如果您更喜欢一些视频指南,可以在此处查看:https ://www.youtube.com/watch?v=_GBBAAC_dcs&ab_channel=TILthings


推荐阅读