原文链接:http://www.iamlintao.com/7300.html
转载请注明:26点的博客 » thinkphp框架中 union查询后的分页方式

有个需求是从两个独立的表中个子取出字段,然后合并显示并且要分页。

感谢网友的思路和代码:

$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.' a')
        ->field('...')
        ->group('...')
        ->paginate(5);
    return json($res);

实际应用是这样的:

$_content_sql = Db::name("content")
->field("content_id as id,title ,'detail' as type,views,'0' as downloadNum,create_time ")
->where(" dt_content.title  like '%车%' ")
->group('content_id')
->buildSql();

$_link_sql = Db::name("link")
->field("id ,title,'info' as type,views,(base_jump_num + jump_num) as downloadNum,create_time ")
->where(" title  like '%车%' ")
->union([$_content_sql])->buildSql();

$list_page = Db::table($_link_sql.' a')
->paginate($this->pageShow);