JustDoItTomorrow
4/28/2018 - 3:40 PM

查询构造器

<?php
$result = Db::name('data')
    ->where('id', 1)
    ->find();

$result = Db::name('data')
    ->where('id', '=', 1)
    ->find();

$result = Db::name('data')
    ->where('id', '>=', 1)
    ->limit(10)
    ->select();
    
$result = Db::name('data')
	// id 是 1、2、3 其中的数字
    ->where('id', 'in', [1, 2, 3])
    ->select();
    
$result = Db::name('data')
    // id 在 5到8之间的
    ->where('id', 'between', [5, 8])
    ->select();
    
// 多个字段查询
$result = Db::name('data')
// id 在 1到3之间的
    ->where('id', 'between', [1, 3])
// name 中包含think
    ->where('name', 'like', '%think%')
    ->select();
    
// 查询null
$result = Db::name('data')
  ->where('name', 'null')
  ->select();
  
// 批量查询
$result = Db::name('data')
    ->where([
        'id'   => ['between', '1,3'],
        'name' => ['like', '%think%'],
    ])->select();
    
// 视图查询
$result = Db::view('user','id,name,status')
    ->view('profile',['name'=>'truename','phone','email'],'profile.user_id=user.id')
    ->where('status',1)
    ->order('id desc')
    ->select();

// 闭包查询
$result = Db::name('data')->select(function ($query) {
    $query->where('name', 'like', '%think%')
        ->where('id', 'in', '1,2,3')
        ->limit(10);
});

// 获取id为8的data数据的name字段值
$name = Db::name('data')
    ->where('id', 8)
    ->value('name');
    
// 获取data表的name列
$list = Db::name('data')
    ->where('status', 1)
    ->column('name');
    
// 统计data表的数据
$count = Db::name('data')
    ->where('status', 1)
    ->count();

// 统计user表的最高分
$max = Db::name('user')
    ->where('status', 1)
    ->max('score');
<?php
// 查询创建时间大于2016-1-1的数据
$result = Db::name('data')
    ->whereTime('create_time', '>', '2016-1-1')
    ->select();
dump($result);

// 查询本周添加的数据
$result = Db::name('data')
    ->whereTime('create_time', '>', 'this week')
    ->select();
dump($result);

// 查询最近两天添加的数据
$result = Db::name('data')
    ->whereTime('create_time', '>', '-2 days')
    ->select();
dump($result);

// 查询创建时间在2016-1-1~2016-7-1的数据
$result = Db::name('data')
    ->whereTime('create_time', 'between', ['2016-1-1', '2016-7-1'])
    ->select();
dump($result);

// 获取今天的数据
$result = Db::name('data')
    ->whereTime('create_time', 'today')
    ->select();
dump($result);  

// 获取昨天的数据
$result = Db::name('data')
    ->whereTime('create_time', 'yesterday')
    ->select();
dump($result);  

// 获取本周的数据
$result = Db::name('data')
    ->whereTime('create_time', 'week')
    ->select();   
dump($result);      

// 获取上周的数据
$result = Db::name('data')
    ->whereTime('create_time', 'last week')
    ->select(); 
dump($result);