yii\db\Query::limit() 函数不限制记录 - Yii2

yii\db\Query::limit() function not limiting the records - Yii2

下面是我用来从我的 table(s) 获取数据以创建 REST api.

的代码
$query = new yii\db\Query();
$sql = $query
    ->select('a.vehicle_number, b.device_id, b.dated, b.speed, b.ignition, b.latitude, b.longitude')
    ->from('tk103_devices a, tk103_current_location b')
    ->where('a.device_id = b.device_id AND a.transporter_id='.$id)
    ->orderBy(['a.vehicle_number'=>SORT_ASC])
    ->limit(1);

$dataProvider = new ActiveDataProvider([
    'query'=>$sql
    ]);
return array('count_flag'=>$countFlag, 'dataProvider'=>$dataProvider->getModels());

根据 Yii 官方文档 http://www.yiiframework.com/doc-2.0/yii-db-querytrait.html#limit()-detail

当我执行上述查询时,数据提供者正在返回所有记录。

我的代码有什么问题?

ActiveDataProvider 不注意查询限制。

http://www.yiiframework.com/doc-2.0/guide-output-data-providers.html#active-data-provider

从上面摘录link:

Note: If a query already specifies the orderBy clause, the new ordering instructions given by end users (through the sort configuration) will be appended to the existing orderBy clause. Any existing limit and offset clauses will be overwritten by the pagination request from end users (through the pagination configuration).

所以,既然你有固定的数据,使用ArrayDataProvider:

$data = $query
    ->select('a.vehicle_number, b.device_id, b.dated, b.speed, b.ignition, b.latitude, b.longitude')
    ->from('tk103_devices a, tk103_current_location b')
    ->where('a.device_id = b.device_id AND a.transporter_id='.$id)
    ->orderBy(['a.vehicle_number'=>SORT_ASC])
    ->limit(1)
    ->all();

$dataProvider = new \yii\data\ArrayDataProvider(['allModels' => $data]);

自己做了一些功课,我通过更改代码如下找到了上述问题的解决方案:

$query = new yii\db\Query();
$sql = $query
    ->select('a.vehicle_number, b.device_id, b.dated, b.speed, b.ignition, b.latitude, b.longitude')
    ->from('tk103_devices a, tk103_current_location b')
    ->where('a.device_id = b.device_id AND a.transporter_id='.$id)
    ->orderBy(['a.vehicle_number'=>SORT_ASC])
    ->one();

$dataProvider = new ActiveDataProvider([
    'query'=>$sql
    ]);
return array('count_flag'=>$countFlag, 'dataProvider'=>$dataProvider);

根据我的情况,我只想检索第一条记录。所以,我使用 one() 而不是 limit(1)

其次,我将 dataProvider 作为 $dataProvider->getModels() 返回。我只将其更改为 $dataProvider。由于 "ActiveDataProvider does not take care at query limit." 按照下面(或)上面 Fabrizio Caldarelli 的回答,它返回所有检索到的记录。

希望对遇到相关问题的人有所帮助。


要使之前的代码生效,您必须查看下方(或)上方Fabrizio Caldarelli