CodeIgniter 4从数据库展示供应商表数据时出现异常输出问题
问题:CodeIgniter中var_dump返回Result对象而非表数据
我想把supplier表的所有供应商记录展示到视图里,但用var_dump输出数据时,返回的始终是CodeIgniter\Database\MySQLi\Result对象,不是表内容,表名和数据库配置都没问题。
输出内容:
object(CodeIgniter\Database\MySQLi\Result)#81 (8) { ["connID"]=> object(mysqli)#78 (18) { ["affected_rows"]=> int(6) ["client_info"]=> string(13) "mysqlnd 8.2.0" ["client_version"]=> int(80200) ["connect_errno"]=> int(0) ["connect_error"]=> NULL ["errno"]=> int(0) ["error"]=> string(0) "" ["error_list"]=> array(0) { } ["field_count"]=> int(3) ["host_info"]=> string(20) "localhost via TCP/IP" ["info"]=> NULL ["insert_id"]=> int(0) ["server_info"]=> string(15) "10.4.27-MariaDB" ["server_version"]=> int(100427) ["sqlstate"]=> string(5) "00000" ["protocol_version"]=> int(10) ["thread_id"]=> int(115) ["warning_count"]=> int(0) } ["resultID"]=> object(mysqli_result)#80 (5) { ["current_field"]=> int(0) ["field_count"]=> int(3) ["lengths"]=> NULL ["num_rows"]=> int(6) ["type"]=> int(0) } ["resultArray"]=> array(0) { } ["resultObject"]=> array(0) { } ["customResultObject"]=> array(0) { } ["currentRow"]=> int(0) ["numRows":protected]=> NULL ["rowData"]=> NULL }
相关代码与配置
SupplierController代码
<?php namespace App\Controllers; use App\Models\SupplierModel; use CodeIgniter\API\ResponseTrait; class SupplierController extends BaseController { use ResponseTrait; function __construct() { $this->supplierModel = new SupplierModel(); } public function index() { $model = new SupplierModel(); $dataSupplier = $model->get(); var_dump($dataSupplier); // return view('pages/Supplier'); } }
SupplierModel代码
<?php namespace APP\Models; use CodeIgniter\Model; use CodeIgniter\API\ResponseTrait; use CodeIgniter\Exceptions; use CodeIgniter\Exceptions\PageNotFoundException; use Exception; use CodeIgniter\Config\Database; class SupplierModel extends Model { use ResponseTrait; protected $table = 'supplier'; protected $primaryKey = 'id'; protected $allowedFields = ['name', 'vendor']; public function get() { $db = \Config\Database::connect(); $builder = $db->table('supplier'); $data = $builder->get(); return $data; } }
数据库表截图

.env配置截图

问题原因与解决方法
原因
你在Model的get()方法中,直接返回了$builder->get()的结果,而这个方法返回的是CodeIgniter的Result查询结果对象,不是直接的数据集。需要调用Result对象的方法来提取实际数据。
解决方法
修改SupplierModel中的get()方法,调用Result对象的getResultArray()(返回数组格式)或getResultObject()(返回对象格式)来获取实际数据:
public function get() { $db = \Config\Database::connect(); $builder = $db->table('supplier'); $query = $builder->get(); // 返回数组格式的数据集 return $query->getResultArray(); // 或者返回对象格式:return $query->getResultObject(); }
另外,既然你的Model已经继承了CodeIgniter的Model类,可以直接使用父类的方法简化代码,不用手动连接数据库和创建builder:
public function get() { // 直接使用父类的findAll()方法获取所有数据 return $this->findAll(); }
修改后,再用var_dump输出$dataSupplier就能看到表中的实际数据,之后即可将数据传给视图展示。
内容的提问来源于stack exchange,提问作者Rafly Andrian
相关产品推荐
相关产品推荐

