我是代码点火器的新手,我的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>
这是我的架构
尝试使用以下代码:
使用m_city
连接m_state
表,如下所示:(最好使用查询生成器类来获得结果(
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
如果您有像这样的状态表
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查询。
使用以下查询
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