php - 如何在 Codeigniter 4 的单个控制器中访问两个不同的模型?
问题描述
我是 Codeigniter 4 的新手,所以我在问这个问题。
实际上,我有两个不同的模型。
首先是 tbl_user。
里面有很多字段 tbl_user(id, name,duty_station,enlistment_date,dob) // 这里 id 是主键。
其次是用户界面。
usermos 有四个字段 [id, user_id, mos_id, additional_mos_id] //这里id是主键,user_id是tbl_user的外键
我已经生成了 get_profile 的控制器...
我想将usermos
模型访问到get_profile
控制器中。
以下是我的代码
标头
<?php namespace App\Controllers;
use CodeIgniter\RESTful\ResourceController;
use App\Models\MosModel;
use App\Models\Additional_mosModel;
use App\Models\Api_auth_model;
use App\Models\Api_Usermos_Model;
控制器
public function get_profile()
{
if (($this->request->getMethod() == 'post') && ($_SERVER['PHP_AUTH_USER'] == AUTHUSER_NAME) && ($_SERVER['PHP_AUTH_PW'] == AUTH_PASSWORD)) {
if(!empty($this->request->getPost('id'))){
$user_api_mos_model = new Api_Usermos_Model();
$usermos = $this->user_api_mos_model->findAll();
print_r($usermos);
exit;
if($profile){
if($usermos){
}
$selected_mos = $this->getMosFromID($usermos[0]['mos_id']);
$selected_add_mos = $this->getAdd_MosFromID($usermos[0]['additional_mos_id']);
$profile['badge'] = $this->getBadgeFromID($profile['badge_id']);
// exit;
return $this->respond([
"status" => "Success",
"message" => "Profile found.",
"Common" => ["Title" => "Load Profile API", 'version' => '1.0', 'Description' => 'Load Profile API', 'Method' => 'POST'],
"Response" => ["Userdata" => $profile,"mos" => $selected_mos,"additonal_mos" => $selected_add_mos]
]);
}else{
return $this->respond([
"status" => "Fail",
"message" => "Profile Not found.",
"Common" => ["Title" => "Load Profile API", 'version' => '1.0', 'Description' => 'Load Profile API', 'Method' => 'POST'],
"Response" => ["Value" => 'Profile Not found.']
]);
}
}
}
}
感谢您宝贵的时间。
解决方案
只需在控制器页面标题部分的顶部定义模型的命名空间并在该控制器页面中使用。例如:
<?php namespace App\Controllers;
use app\models\User;
use app\models\Usermos;
Class UserController extend controller {
public function actionProfile (){
$user = new User();
$user_mos = new Usermos();
}
}
推荐阅读
- python - 有没有办法在 Dash 中重新启动回调中间函数?
- reactjs - 在类组件中多次导出反应问题
- mysql - 有没有办法对以单数和复数形式找到的数据表中的任何单词进行 mySQL 搜索?
- javascript - Shopify 购买按钮最大数量
- javascript - 制表器可移动行 - 如何一次选择/移动多个项目
- c++ - 从 C++ 中的函数返回不同的数据类型
- gradle - 无法使用依赖的 FAT jar 构建 gradle
- scala - 获取 Option 值或映射到 eitherT 的惯用方式
- powershell - 如何在没有密码的 USER 帐户上远程运行 powershell 脚本?
- vb.net - VB.Net 自定义位图