ActiveDataProvider和SQLDataProvider之间有什么区别?

时间:2017-12-05 08:15:51

标签: yii2

我有点困惑。我想知道Yii2 ActiveDataProviderSQLDataProvider之间有什么区别?我正在寻找它的文档,但也无法得到它。

有人可以解释我何时应该使用其中一种?它有什么区别?

感谢您的时间。

1 个答案:

答案 0 :(得分:3)

SqlDataProvider使用原始SQL语句,该语句用于获取所需数据,ActiveDataProvider可以使用yii\db\Queryyii\db\ActiveQuery 对象

SqlDataProvider示例:

$provider = new SqlDataProvider([
   'sql' => 'SELECT * FROM post WHERE status=:status',   //HERE
   'params' => [':status' => 1],
   'totalCount' => $count,
   'pagination' => [
       'pageSize' => 10,
   ],
   'sort' => [
       'attributes' => [
           'title',
           'view_count',
           'created_at',
       ],
   ],
]);

ActiveDataProvider示例:

$query = Post::find()->where(['status' => 1]);     // ActiveQuery here

$provider = new ActiveDataProvider([
    'query' => $query,                // and here
    'pagination' => [
        'pageSize' => 10,
    ],
    'sort' => [
        'defaultOrder' => [
            'created_at' => SORT_DESC,
            'title' => SORT_ASC, 
        ]
    ],
]);