-1

我是codeigniter的新手,我的city表结构就像

id,name,state_id

现在在视图中我得到了城市的所有数据,但我也想打印州名。但在city表中我只有州名。所以我怎样才能在视图中获得州名

这是我的控制器。

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>

这是我的架构

4

3 回答 3

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 查询。

于 2018-07-19T06:13:29.813 回答
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

于 2018-07-19T06:13:47.483 回答
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
于 2018-07-19T06:15:38.293 回答