CodeIgniter 3中Unknown column 'table_book.year'错误求助
问题修复方案
核心问题分析
- 数据库查询逻辑错误:调用
retrieveBook()不传参数时,SQL仅从table_autor表查询,但SELECT语句包含table_book的字段,数据库无法识别这些字段导致报错。 - 字段拼写不匹配:SELECT里的
tittle与表结构的titulo不符;View里的tit也和实际字段名不匹配。 - 需求逻辑偏差:要获取书籍信息,无论是否传
id_book,都必须关联table_book表,否则无法拿到书籍相关数据。
修复后的Model代码
function retrieveBook($id_book = null) { // 修正字段拼写:tittle -> titulo,确保查询的字段存在于表结构中 $this->db->select('table_autor.name as name, table_book.year, table_book.titulo, table_book.file'); $this->db->from('table_autor'); // 固定关联table_book表,保证始终能获取书籍数据 $this->db->join('table_book', 'table_autor.id_autor = table_book.id_autor'); if($id_book != null){ $this->db->where('table_book.id_book', $id_book); } $result = $this->db->get(); if ($this->db->error()) { $error = $this->db->error(); echo 'Error: '. $error['message']; } echo '</br>'; echo $this->db->last_query(); return $result; }
修复后的View代码
<?php if($retrieveBook && $retrieveBook->num_rows() > 0):?> <?php foreach($retrieveBook->result() as $key=>$bookItem):?> <tr> <td><?=$bookItem->name?></td> <!-- 修正字段名:tit -> titulo,与SELECT语句中的字段保持一致 --> <td><?=$bookItem->titulo?></td> <td><?=$bookItem->year?></td> <td><?=$bookItem->file?></td> </tr> <?php endforeach;?> <?php else:?> <tr> <td colspan="4">暂无书籍数据</td> </tr> <?php endif;?>
额外优化建议
- 不要在Model中直接
echo错误信息和SQL语句,建议通过日志记录或把错误信息返回给Controller处理,避免破坏页面输出结构。 - 可以给字段设置别名简化View调用,比如
table_book.titulo as title,这样View里用$bookItem->title更直观。 - 确认
table_autor和table_book的id_autor字段类型一致,避免隐式类型转换影响查询效率。
内容的提问来源于stack exchange,提问作者user3k
相关产品推荐
相关产品推荐

