链式查询
通过主键获取数据
User::find(100);
//SQL: SELECT * FROM user WHERE id = 100;
User::find(100, 'id, nickname, avatar');
//SQL: SELECT id, nickname, avatar FROM user WHERE id = 100;
查询一条数据
User::where('name', 'Tommy')->row();
//SQL: SELECT * FROM user WHERE name = 'Tommy' LIMIT 1;
User::where('name', 'Tommy')->fields('id, nickname, avatar')->row();
//SQL: SELECT id, nickname, avatar FROM user WHERE name = 'Tommy' LIMIT 1;
获取一列
一维数组
User::where('id', 'in', [22, 68, 33])
->column('nickname');
//返回
Array
(
[0] => Tommy
[1] => Tomener
[2] => Yob
)
关联数组
// id作为键,nickname作为值
User::where('id', 'in', [22, 68, 33])
->column('nickname', 'id');
//返回
Array
(
[22] => Tommy
[68] => Tomener
[68] => Yob
)
关联数组(值为数组)
// id作为键,user信息数组作为值
User::where('id', 'in', [22, 68, 33])
->column('nickname, avatar', 'id');
//返回
Array
(
[22] => Array('id' => 22, nickname' => 'Tommy', 'avatar' => '22.jpg'),
[68] => Array('id' => 68, nickname' => 'Tomener', 'avatar' => '68.jpg'),
[33] => Array('id' => 33, nickname' => 'Yob', 'avatar' => '33.jpg'),
)
值查询
$nickname = User::where(22)->value('nickname');
var_dump($nickname);
//打印出
string(7) "Tommy"
查询多条数据
User::where(['sex' => 1, 'level' => 5])->select();
//SQL: SELECT * FROM user WHERE sex = 1 AND level = 5;
查询条数限制
User::where(['sex' => 1, 'level' => 5])
->limit(10)
->select();
//SQL: SELECT * FROM user WHERE sex = 1 AND level = 5 LIMIT 10;
分页
$page = ['limit' => 10, 'p' => 1];
User::where(['sex' => 1, 'level' => 5])
->page($page)
->select();
//SQL: SELECT * FROM user WHERE sex = 1 AND level = 5 LIMIT 0, 10;
排序
User::where('type', 2)
->field('uid, nickname, avatar')
->order('created DESC, id DESC')
->limit(10)
->select();
SQL: SELECT uid, nickname, avatar FROM user WHERE type = 2 ORDER BY created DESC, id DESC LIMIT 10;
分组
User::where(['created' => ['between', 1470000000, 1490000000]])
->field('COUNT(*) num, SUM(balance) balance')
->group('level')
->select();
//SQL: SELECT COUNT(*) num, SUM(balance) balance FROM user where created between 1470000000 AND 1490000000 GROUP BY level;