【问题标题】:List users from database with CodeIgniter 4使用 CodeIgniter 4 从数据库中列出用户
【发布时间】:2020-10-07 11:38:06
【问题描述】:

我是 CodeIgniter 4 的新手,我需要显示一个用户列表,其中包含来自多个表的用户详细信息: 用户、users_details、user_contact_details、公司、公司职位、部门。 在表 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>

【问题讨论】:

  • 您希望输出的准确程度如何?只有一个数组,还是一个数组只包含信息,键包含其余信息?
  • 像一个数组一样输出,其中仅包含信息,而键包含其余信息。谢谢

标签: php codeigniter-4


【解决方案1】:

您需要详细说明您的问题实际上是什么以获得真正的“答案”,但我有两分钱可以给您,这对于评论来说有点太长了。

我最近有一个使用 CI4 的项目使我处于同样的境地:我的大部分业务逻辑都需要跨多个表的信息,但是使用单个模型来跨多个表并不适合 CI 的一个设计每个表的模型。

我仍然创建了所有“内部”CI 扩展模型类,每个类都代表一个表,但我还创建了自己的“外部”模型类型类,它扩展 CI 的模型类。

这个“外部”模型不能直接访问任何数据库,而是充当业务逻辑和“内部”模型的“容器”;同时,“内部”模型将其边界保持在单个表中,不访问其关联表之外的任何数据(例如,没有 joins)。

当控制器转到模型执行业务逻辑时,它转到的模型实际上是我的“外部”模型,而不是 CI 扩展的“内部”模型之一。然后从那个“外部”模型中,我可以构建/与我需要的任何“内部”模型进行交互,具体取决于我需要哪些表来执行请求的业务逻辑,以获取我需要完成请求的所有数据。

因此,流程看起来更像View &lt;&gt; Controller &lt;&gt; Outer Model &lt;&gt; Inner Models,而不是View &lt;&gt; Controller &lt;&gt; Model

我最终最喜欢这种方法,因为它 a) 使代码整体更具可读性,b) 仍然包含模型的所有业务逻辑,并且 c) 仍然允许您充分利用 CI 扩展模型的功能 (内置的 getter/setter、Entity 类等)。

同样,这不是对您问题的具体答案,但可能是您从整体上考虑问题的有效方式。

【讨论】:

    【解决方案2】:

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

    首先,您的模型应该有更多信息才能像这样使用此功能:

    <?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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-14
      • 2020-04-22
      • 2020-07-12
      • 2021-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多