php - codeigniter 多个选择查询相互依赖

标签 php mysql codeigniter

我是 codeigniter (CI) 的新手,我需要选择登录用户的比赛和总票数,假设用户和比赛表具有多对多关系,比赛项目也是如此。 我需要选择用户的比赛以及与该用户相关的所有项目投票;我还需要选择所有比赛的投票并获得每场比赛的总票数。 毕竟,所有的结果都必须显示在一个 View 中(这是最复杂的部分),例如,我不能在一个模型中操作所有这些以及如何将许多数组返回到 Controller ,等等。

这是我的 Controller 的一个例子:

<?php
class User_id extends CI_Controller{

    function __construct()
    {
       parent::__construct();
       $this->load->helper(array('form', 'url'));
       $this->load->library('session');
    }

    function index(){
        $this->load->view('v_user_id');
    }

    function view_comp(){
        $c_id = $this->input->post('id');
        $this->session->set_userdata('c_id',$c_id);
        $s_id = $this->session->userdata('c_id');
        $this->load->model('comps_model');
        $data['rows'] = $this->comps_model->getComps($s_id);
    }           
}
?>

这是我的目标模型,它应该包含“所有选择查询”并返回前面提到的“所有结果”:

<?php
class Comps_model extends CI_Model{

    function getComps($id){

        $this->load->database(); 
        $id = $this->db->query("select competition_id from user_competition        where user_id='".$id."'");
        if($id->num_rows() > 0){
            foreach($id->result() as $id_row){
                $comp_name = $this->db->query("select competition_title from competition where competition_id='".$id_row->competition_id."'");
                if($comp_name->num_rows() > 0) {
                    //all the stuff should go here or something like that
                }
            }
        }
    }

}
?>

如果能提供一些代码示例,我将不胜感激:)

最佳答案

你可以这样试试

function getComps($id)
{
    $this->load->database();
    $data=array(); 
    $id = $this->db->query("select competition_id from user_competition where user_id='".$id."'");
    if($id->num_rows() > 0)
    {
        $data=$id->result_array();
    }
    foreach($data as $key=>$each)
    {
        //adding competition title
        $comp_name = $this->db->query("select competition_title from competition where competition_id='".$each['competition_id']."'");
        if($comp_name->num_rows()>0){
            $temp=$comp_name->row_array();    
            $data[$key]['competition_title']=$temp['competition_title'];
        }
        else
        {
            $data[$key]['competition_title']="";
        }
        //other calculations will go on 
    }
    echo "<pre>";print_r($data);die;
}

如果你每次都这样做,你将计算一些值并将该值插入现有数据数组中。例如,如果你计算总票数,然后在 foreach 循环中计算总数并插入到数组中,如

  $data[$key]['total_votes']=$temp['total_votes'];

如果您遇到任何问题,请告诉我。

关于php - codeigniter 多个选择查询相互依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18871026/

相关文章:

mysql - 错误代码 1046 : No database Selected

mysql - 在缩放的 OpenShift Online 应用程序中, bundle 安装在 mysql gem 上失败

php - 尽管在本地服务器中正常工作,但 cpanel 中的 codeigniter Web 应用程序出现错误

php - 删除所有Href和youtube URL并获取ID

php - 使用 session 显示特定组的文本

php - 从当前 php 刷新另一个页面

php - 更好地解析数组或添加数据库调用?

php - 在 PHP 中读取 xlsx 文件

php - 如何通过 URL 获取多个数组到 iOS 应用程序

php - 为什么在 CodeIgniter 中调用 sess_update?