查询数据库
1. 使用模型查询(推荐)
// 在控制器中
use app\common\model\YourModel;
public function index()
{
// 1. 查询所有数据
$list = YourModel::select();
// 2. 查询单条数据
$data = YourModel::find(1); // 主键查询
$data = YourModel::where('id', 1)->find(); // 条件查询
// 3. 条件查询
$list = YourModel::where('status', 1)
->where('type', '>', 0)
->order('id', 'desc')
->select();
// 4. 分页查询
$list = YourModel::where('status', 1)->paginate(10);
return $list;
}
复杂查询示例
// 多条件查询
$list = YourModel::where(function($query) {
$query->where('status', 1)
->whereOr('status', 2);
})
->where('create_time', '>', '2023-01-01')
->order('id', 'desc')
->limit(10)
->select();
// IN 查询
$list = YourModel::whereIn('id', [1, 2, 3, 4])->select();
// BETWEEN 查询
$list = YourModel::whereBetween('create_time', ['2023-01-01', '2023-12-31'])->select();
// LIKE 查询
$list = YourModel::where('name', 'like', '%关键词%')->select();
2. 使用 Db 类查询
基础 Db 查询
use think\facade\Db;
public function queryWithDb()
{
// 1. 查询单条数据
$data = Db::name('your_table')->where('id', 1)->find();
// 2. 查询多条数据
$list = Db::name('your_table')->where('status', 1)->select();
// 3. 查询某个字段的值
$name = Db::name('your_table')->where('id', 1)->value('name');
// 4. 查询某一列的值
$names = Db::name('your_table')->where('status', 1)->column('name');
// 5. 统计数量
$count = Db::name('your_table')->where('status', 1)->count();
// 6. 最大值、最小值、平均值
$max = Db::name('your_table')->max('price');
$min = Db::name('your_table')->min('price');
$avg = Db::name('your_table')->avg('price');
$sum = Db::name('your_table')->sum('price');
}
复杂 Db 查询
// 联表查询
$list = Db::name('user u')
->field('u.*, p.phone, p.address')
->join('user_profile p', 'u.id = p.user_id')
->where('u.status', 1)
->order('u.id', 'desc')
->select();
// 分组查询
$list = Db::name('order')
->field('user_id, COUNT(*) as order_count, SUM(amount) as total_amount')
->where('create_time', '>', '2023-01-01')
->group('user_id')
->having('order_count > 5')
->select();
// 子查询
$subQuery = Db::name('order')
->field('user_id, MAX(create_time) as last_order_time')
->group('user_id')
->buildSql();
$list = Db::table([$subQuery => 'sub'])
->join('user u', 'sub.user_id = u.id')
->field('u.*, sub.last_order_time')
->select();
No comments to display
No comments to display