联合查询的Yii2自定义paginaion

时间:2016-04-14 07:15:52

标签: pagination yii2-advanced-app

我想在Yii2中实现自定义分页。这是我的代码

$connection = Yii::$app->getDb();
$name       =   $_GET['name'];
$query      =   '
                SELECT name FROM user WHERE name LIKE "%.'$name'.%"" 
            UNION
                SELECT name FROM user2 WHERE name LIKE "%.'$name'.%"" 
            UNION
                SELECT name FROM user3 WHERE name LIKE "%.'$name'.%"" 
            UNION
                SELECT name FROM user4 WHERE name LIKE "%.'$name'.%"" 
            ';              
$result      = $connection->createCommand($query)->queryAll();

请让我知道如何在Yii2中实现分页

2 个答案:

答案 0 :(得分:3)

Plz试试这个

$totalCount =   0;

$name       = $_GET['name'];
$connection = Yii::$app->getDb();
$limit      =   10;

$from       =   (isset($_GET['page'])) ? ($_GET['page']-1)*$limit : 0; // Match according to your query string

$sql        =   '
            SELECT name FROM user WHERE name LIKE "%.'$name'.%"" 
        UNION
            SELECT name FROM user2 WHERE name LIKE "%.'$name'.%"" 
        UNION
            SELECT name FROM user3 WHERE name LIKE "%.'$name'.%"" 
        UNION
            SELECT name FROM user4 WHERE name LIKE "%.'$name'.%"" 
        ';
$command = $connection->createCommand($sql.' LIMIT '.$from.','.$limit);

$count   = $connection->createCommand('SELECT COUNT(*) as total FROM ('.$sql.') a')->queryAll();

$result         = $command->queryAll();

$totalCount     =   $count[0]['total'];

$pages = new Pagination(['totalCount' => $totalCount, 'pageSize' => $limit]);       

答案 1 :(得分:0)

这是更合适的Yii2方式:

在控制器中:

    $page = Yii::$app->request->get('page', 1);
    $limit = Yii::$app->request->get('per-page', 10);
    $from = ($page-1)*$limit; 

    //Get the db connection
    $db = new yii\db\Connection(Yii::$app->db);

    //prepare SQL query
    $sql = '
            SELECT name FROM user WHERE name LIKE "%.'$name'.%"" 
        UNION
            SELECT name FROM user2 WHERE name LIKE "%.'$name'.%"" 
        UNION
            SELECT name FROM user3 WHERE name LIKE "%.'$name'.%"" 
        UNION
            SELECT name FROM user4 WHERE name LIKE "%.'$name'.%"" 
        ';

    //Fire it!
    $result =   $db->createCommand($sql.' LIMIT '.$from.','.$limit)->queryAll();
    $count   = $db->createCommand('SELECT COUNT(*) as total FROM ('.$sql.') a')->->queryScalar();

    $pagination = new \yii\data\Pagination(['totalCount' => $count, 'pageSize' => $limit]);             
    return $this->render('your-view', [
        'result' => $result,
        'pagination' => $pagination,
    ]);

然后在您的视图中的任何位置:

echo \yii\widgets\LinkPager::widget([
    'pagination' => $pagination,
]);

我自己得到E-Avni Tech答案的帮助。如果我的回答有帮助,请向他投票。