代码点火器如何知道如何将参数从控制器传递到模型


How does codeigniter know how to pass parameters from controller to the model

我开始学习代码点火器的活动记录,并使用从控制器传递到模型的参数查询我的数据库。

首先,我将id从控制器传递给模型,这就起作用了。

控制器

function bret($id){
$this->load->model('school_model');
$data = $this->school_model->get_city_and_population($id);
foreach ($data as $row)
{
echo "<b>Name Of The City</b>...........". $row['Name'];
echo "<br/>";
echo "<b>Total Population</b>...........".$row['Population'];
}
}

型号

function get_city_and_population($id){
$this->db->select('Name,Population');
$query = $this->db->get_where('city', array('ID'=>$id));
return $query->result_array();
}

我继续输入了多个参数,预计会失败,但这有效,但我不太确定为什么有效或什么有效。

控制器

public function parameters($id,$name,$district){
    $this->load->model('school_model');
    $data = $this->school_model->multiple_parameters($id,$name,$district);
    foreach ($data as $row)
    {
    echo "<b>Total Population</b>...........".$row['Population'];
    }
    }

型号

function multiple_parameters($id,$name,$district){
$this->db->select('Population');
$query = $this->db->get_where('city', array('ID'=>$id,'Name'=>$name,'District'=>$district));
return $query->result_array();
}

在我的多参数示例中,我访问了http://example.com/env/at/index.php/frontpage/parameters/7/Haag/Zuid-Holland/

这里,我知道名称Haag在id 7中,而区域是Zuid-Holland

以下是我的问题。codeigniter如何知道如何将参数从url传递到模型?其次,如果我像7/Haag/Zuid-Hollandes/一样有点错误怎么办?我如何向用户显示,该url是错误的,并回退到默认值,而不是在参数错误时显示为空?。

//In codeiginter URI contains more then two segments they will be passed to your function as parameters.
//if Url: http://example.com/env/at/index.php/frontpage/parameters/7/Haag/Zuid-Holland/
//Controller: forntpage
public function parameters($id,$name,$district){
   echo $id.'-'$name.'-'.$district;
}
//and if you are manually getting url from segment & want to set default value instead of blank then use following:

public function parameters(
$this->load->helper("helper");
$variable=$this->uri->segment(segment_no,default value);
//$id=$this->uri->segment(3,0);
}
//or
 //Controller: forntpage
 public function parameters($id='defaultvalue',$name='defaultvalue',$district='defaultvalue'){
   echo $id.'-'$name.'-'.$district;
}

这只是CI中的简单uri映射,或者uri-param绑定(如果愿意的话)
当你有这样的方法时:

public function something($param1, $param2) {
    // get from: controller/something/first-param/second-param
}

这意味着您的uri段将作为参数传递给控制器方法。

上述方法可以写成:

public function something() {
    $param1 = $this->uri->segment(3);
    $param2 = $this->uri->segment(4);
    // segment 1 is the controller, segment 2 is the action/method.
}

您需要明白,您必须手动检查uri段是否正是您想要的,因为CI除了此映射之外不做任何其他事情。

接下来,若你们想要一些默认值,下面的语句是正确的:

public function something($param1 = 'some default value', $param2 = 'other value') {
// get from: controller/something/first-param/second-param
}

也就是说,如果传递了一个类似:/controller/something的url,您仍然会得到默认值。传递controller/something/test时,您的第一个参数将被url中的参数覆盖(测试)。

差不多了。