Startmvc支持通过“连贯操作”方式增/删/改/查数据,也支持原生sql语句操作。操作数据库前,请配置好数据库信息config/database.php
字段选择select()
select('id, name')
select(['id', 'name', ...])
如果不使用select方法,默认是查询所有字段(*)
更多选择功能
方法: count()
sum()
avg()
min()
max()
sum('amount')
sum('amount', 'totalAmount')
选择表table()/from()
table()和from()功能是一样的,用哪个都行
table('products')
table(['products as p', 'images as i'])
联合查询Join
方法有: join()
,leftJoin()
rightJoin()
innerJoin()
leftOuterJoin()
rightOuterJoin()
fullOuterJoin()
leftJoin('images', 'products.id', 'images.productId')
leftJoin('images', 'products.id = images.productId')
leftJoin('images ON products.id = images.productId')
加入子节点查询joinNode()
通过这个方法,你可以构造一个子查询,将查到的数据作为结果的一个子元素。如果当前没有设置groupBy,会自动添加主表的id字段作为分组依据
条件语句Where
where方法支持四种使用方式:
1. 数组方式 - 多个条件AND连接
2. 简单条件 - 等于判断
3. 带运算符的条件
4. 原生SQL条件 - 支持参数绑定
支持的条件方法:
- where() // 基本条件
- orWhere() // OR条件
- notWhere() // NOT条件
- orNotWhere() // OR NOT条件
- whereNull() // IS NULL条件
- whereNotNull() // IS NOT NULL条件
使用示例:
条件组合grouped
介于between()
方法: between()
,orBetween()
,notBetween()
,orNotBetween()
不为空Is Null - Not Null
方法 isNull()
,orIsNull()
,notNull()
,orNotNull()
isNull('slug')
isNull(['slug', ...])
包含In
方法: in()
,orIn()
,notIn()
,orNotIn()
位置查询Find In Set
方法有: findInSet()
,orFindInSet()
,notFindInSet()
,orNotFindInSet()
模糊查询Like - Not Like
方法: like()
,orLike(
),notLike()
,orNotlike()
like('name')
like(['name', ...])
排序Order
默认是降序排列desc
order('id')
order('id desc')
order('id', 'desc')
order('rand()')
分组查询Group
group('id')
group(['id', 'name'])
筛选Having
HAVING 子句可以让我们筛选分组后的各组数据,一般与分组group配合使用
having('stock', 5)
having('stock > 5')
having('stock > ?', 5)
限制查询Limit - Offset
一般用于限制数量Limit, 偏移Offset, 和分页操作Paging.