根据视图中的ID从数据库获取数据:Codeigniter

时间:2018-07-19 05:56:07

标签: php codeigniter codeigniter-3 codeigniter-query-builder

我是新手,可以对city表结构进行代码初始化

id,name,state_id

现在在视图中我可以获取城市的所有数据,但我也想打印州名。但是在city表中,我只有州ID。所以如何在视图中获取州名

这是我的控制器。

public function city(){
        $query = "SELECT * FROM ".CITYTABLE." ORDER BY name ASC";
        $citydata = $this->masterModel->_get_data("",$query);
        $this->create_template('manage-city', 'admin',compact('citydata'));
}

我的看法就像

<tbody>
  <?php
    $i=1;
    foreach ($citydata as $value) { 
      if($value->status == 1){
        $status = "<span class='label label-success'>Active<span>";
      }else{
        $status = "<span class='label label-warning'>Deactive<span>";
      }
  ?>
  <tr>
    <th scope="row"><?= $i++ ?></th>
    <td><?= ucfirst($value->name) ?></td>
    <td><?= $value->state_id ?></td>//HEREEEEEEEEEEE IS I WANT TO SHOW NAME OF STATE/*****/
    <td><?= $status ?></td>
    <td>
      <?php echo anchor("master/edit_city/{$value->id}","<i class='fa fa-pencil'></i> Edit",['class'=>"btn btn-link"]) ?>
      <span class="rmv-city" data-state="<?=$value->id?>"><i class="fa fa-trash"></i> Delete</span>
    </td>
  </tr>
  <?php } ?>
</tbody>

这是我的 Schema

3 个答案:

答案 0 :(得分:1)

如果您有一个状态表,例如

Table Name: states 
Fields : state_id, state_name
//City tbl
Table Name: city
Fields: id,name,state_id

您可以使用将两个表连接起来的方法,

public function city(){
   $query = "SELECT c.id, c.name, s.state_name FROM city c join states s
             on c.state_id = s.state_id ORDER BY c.name ASC";

  $citydata = $this->masterModel->_get_data("",$query);

  $this->create_template('manage-city', 'admin',compact('citydata'));
}

但是,您必须遵循标准的codeigniter查询。

答案 1 :(得分:1)

尝试使用此代码:

通过m_statem_city表一起加入:(最好使用查询生成器类来获取结果)

public function city()
{
    $sql = "SELECT `m_city`.*, `m_state`.`name` as `state_name` 
            FROM `m_city` 
            JOIN `m_state` 
            ON `m_state`.`id` = `m_city`.`state_id` 
            ORDER BY `m_city`.`name` ASC";

    $citydata = $this->masterModel->_get_data("",$sql);
    $this->create_template('manage-city', 'admin',compact('citydata'));
}

更多信息:https://www.codeigniter.com/user_guide/database/query_builder.html

答案 2 :(得分:0)

使用以下查询

SELECT m_city.id,m_city.name,m_state.name AS state_name
FROM m_city
JOIN m_state ON m_city.state_id=m_state.id