Startmvc支持通过“连贯操作”方式增/删/改/查数据,也支持原生sql语句操作。操作数据库前,请配置好数据库信息config/database.php
字段选择select()
$db->select('id, name, code, price')
select('id, name')
select(['id', 'name', ...])
如果不使用select方法,默认是查询所有字段(*)
更多选择功能
方法: count()
sum()
avg()
min()
max()
$db->sum('amount')
sum('amount')
sum('amount', 'totalAmount')
选择表table()/from()
table()和from()功能是一样的,用哪个都行
$db->table('products')...
table('products')
table(['products as p', 'images as i'])
联合查询Join
方法有: join()
,leftJoin()
rightJoin()
innerJoin()
leftOuterJoin()
rightOuterJoin()
fullOuterJoin()
$db->table('products as p')
->leftJoin('images as i', 'p.id', 'i.productId')
->get();
leftJoin('images', 'products.id', 'images.productId')
leftJoin('images', 'products.id = images.productId')
leftJoin('images ON products.id = images.productId')
加入子节点查询joinNode()
通过这个方法,你可以构造一个子查询,将查到的数据作为结果的一个子元素。
$basketData = $db->table('users AS u')
->select('u.*')
->leftJoin('cart AS c', 'c.userId', 'u.id')
->joinNode('cartData', ['name' => 'c.productName', 'quantity' => 'c.quantity'])
->group('u.id')
->first();
Array
(
[id] => 159
[fullName] => John Doe
[email] => john@doe.com
[cartData] => Array
(
[0] => Array
(
[name] => Apple Iphone X 128 GB
[quantity] => 1
)
[1] => Array
(
[name] => Apple Iphone X 256 GB
[quantity] => 1
)
)
)
条件语句Where
方法: where()
orWhere()
notWhere()
orNotWhere()
$db->where('id', 32886)...
where('active', 1)
where('stock >= ? AND active = ?', [2, 1])
where(['stock > ?', 'active > ?'], [2, 1])
where(['stock' => 2, 'active' => 1])
where('stock >= 2 AND active = 1 AND MONTH(updated) = MONTH(NOW())')
条件组合grouped
$db->table('products')
->like('name', '%iphone%')
->grouped(function($q){
$q->in('brandId', [1, 2, 3])->orIn('categoryId', [1, 2, 3]);
})->get();
SELECT * FROM products WHERE name LIKE ? AND (brandId IN(?,?,?) OR categoryId IN(?,?,?))
介于between()
方法: between()
,orBetween()
,notBetween()
,orNotBetween()
$db->between('price', 50, 250)...
不为空Is Null - Not Null
方法 isNull()
,orIsNull()
,notNull()
,orNotNull()
$db->isNull('code')...
isNull('slug')
isNull(['slug', ...])
包含In - Not In
方法: in()
,orIn()
,notIn()
,orNotIn()
$db->in('id', [33922, 31221, 45344, 35444])...
位置查询Find In Set
方法有: findInSet()
,orFindInSet()
,notFindInSet()
,orNotFindInSet()
$db->findInSet('categoryId', 139)...
$db->findInSet('b', 'a,b,c,d'); //返回2
模糊查询Like - Not Like
方法: like()
,orLike(
),notLike()
,orNotlike()
$db->like('name', '%Apple%')...
like('name')
like(['name', ...])
排序Order
默认是降序排列desc
$db->order('id')...
order('id')
order('id', 'asc')
order('id desc, name asc')
order('rand()')
分组查询Group
$db->group('id')...
group('id')
group(['id', 'name'])
筛选Having
HAVING 子句可以让我们筛选分组后的各组数据,一般与分组group配合使用
$db->having('stock', 5)...
having('stock', 5)
having('stock > 5')
having('stock > ?', 5)
限制查询Limit - Offset
一般用于限制数量Limit, 偏移Offset, 和分页操作Paging.
$db->limit(100)...
$db->limit(100, 0)...
$db->limit(100)->offset(0)...