我是 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/