我是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
}
}
}
}
}
?>
我将不胜感激一些代码示例:)
你可以这样尝试
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'];
如果您遇到任何问题,请告诉我。