在 thinkphp 8 中,单次统计或只需要原始字段时,可以直接用 db::name()。需要复用商品的字段格式化、关联或模型行为时,用模型更合适。下面用同一张商品表对照。
用 Db 做一次上架数量统计
示例假定已配置数据库,并有 product 表和 status 字段。Db 查询直接返回统计结果。
$count = \think\facade\Db::name('product')
->where('status', 1)
->count();
return json(['active_products' => $count]);
这个接口只返回一个数量,无需构造商品模型实例。
让模型集中维护价格展示规则
在单应用示例中将类放到 app/model/Product.php。假定 price 存储整数分,price_text 为只读的展示值。
立即学习“PHP免费学习笔记(深入)”;
<?php
namespace app\model;
use think\Model;
class Product extends Model
{
public function getPriceTextAttr($value, $data): string
{
return number_format((int) $data['price'] / 100, 2, '.', '') . ' 元';
}
}选择字段时保留访问器所依赖的 price。展示格式只用于输出,计算仍使用整数分。
用同一条记录核对返回形态
把下面片段放在已有控制器方法里。确保测试商品 ID 1 的 price 是 1250。
$product = \app\model\Product::where('id', 1)->find();
if ($product === null) {
return json(['message' => '商品不存在'], 404);
}
return json(['price_text' => $product->price_text]);预期看到 12.50 元。改用 Db 读取同一行会拿到原始字段,需要自行转换。



















