我是codeigniter(CI)的新手,我需要选择登录用户的比赛和总票数,比方说用户和比赛表有多对多的关系,竞争项目也是如此。 我需要选择与该用户相关的用户竞赛和所有项目投票;我还需要选择所有比赛的选票并获得每个选票的总票数。 毕竟,所有结果必须显示在一个视图中(这是最复杂的部分),例如,我无法操纵一个模型中的所有内容以及如何将许多数组返回到控制器,依此类推。
这是我的控制器的一个例子:
<?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
}
}
}
}
}
?>
我会对一些代码示例表示感谢:)
答案 0 :(得分:1)
您可以尝试这样
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'];
如果您遇到任何问题,请告诉我。