thinkphp5分页

使用fetchSql方法

fetchSql方法表示不进行查询而只是返回构建的SQL语句,并且不仅仅支持select,而是支持所有的CURD查询。

$subQuery = Db::table('think_user') ->field('id,name') ->where('id', '>', 10) ->fetchSql(true) ->select();

生成的subQuery结果为:

SELECT `id`,`name` FROM `think_user` WHERE `id` > 10

使用buildSql构造子查询

$subQuery = Db::table('think_user') ->field('id,name') ->where('id', '>', 10) ->buildSql();

生成的subQuery结果为:

( SELECT `id`,`name` FROM `think_user` WHERE `id` > 10 )

调用buildSql方法后不会进行实际的查询操作,而只是生成该次查询的SQL语句(为了避免混淆,会在SQL两边加上括号),然后我们直接在后续的查询中直接调用。

然后使用子查询构造新的查询:

Db::table($subQuery . ' a') ->where('a.name', 'like', 'thinkphp') ->order('id', 'desc') ->select();

生成的SQL语句为:

SELECT * FROM ( SELECT `id`,`name` FROM `think_user` WHERE `id` > 10 ) a WHERE a.name LIKE 'thinkphp' ORDER BY `id` desc

 

使用例子: 

参考:https://blog.jkloozx.com/?id=163#respond 

1、model用法
$m_acc = model('...');
        $a = $m_acc->field('... as a,...')->where(...)->group('...')->buildSql();
        $b = $m_acc->field('... as a,...')->where(...)->group('...')->buildSql();
        $c = $m_acc->field('... as a,...')->where(...)->group('...')->buildSql();
        $e = $m_acc->field('... as a,...')->where(...)->group('...')->buildSql();
        $e = $m_acc->field('... as a,...')->where(...)->group('...')->union([$a,$b,$c,$d])->buildSql();
        //到这里,已经可以把$e当做一个正常表来进行操作了,什么分页、group by、where随便用,使用"DB::table($e . ' a')"即可
        $res = Db::table($e)->alias('a')   //必须有表别名将之前的查询看成一个表
            ->field('...')
            ->group('...')
            ->paginate(5);
        return json($res);
上面我是根据一个表里字段的不同分出了几个表然后union在一起的,当然也可以使用不同的表来操作,但需要注意的是一定要保证union的几个表必须具有相同的字段,这个
使用filed方法保证union 表的字段一致性即可

2、直接使用controller 用法

        $db = Db::connect('conn1');
       //thinkphp5 不释放field, where 故每次重新连接
        $a =  Db::connect('conn1')->table('a')->field('... as a,...')->joion('.....')->where(...)->group('...');
        $b = Db::connect('conn1')->table('b')->field('... as a,...')->where(...)->group('...')->buildSql();
        $c =Db::connect('conn1')->table('c')->field('... as a,...')->where(...)->group('...')->buildSql();
        $e = Db::connect('conn1')->table('e')->field('... as a,...')->where(...)->group('...')->buildSql();
        $table =  $a->union([$b,$c,$d,$e])->buildSql();   //用表a 去union 其他表
        //到这里,已经可以把$e当做一个正常表来进行操作了,什么分页、group by、where随便用,使用"DB::table($e . ' a')"即可
        $res = Db::connect('conn1')->table($table)->alias('a')   //必须有表别名将之前的查询看成一个表
            ->field('...')
            ->group('...')
            ->paginate(5);
        return json($res);

 

 

 

你可能感兴趣的:(php)