donglinxin8765 2016-04-05 12:11
浏览 476
已采纳

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

Below is the code I'm using to get data from my table(s) for creating 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());

I had set the limit(1) which does "Sets the LIMIT part of the query." as per Yii official doc http://www.yiiframework.com/doc-2.0/yii-db-querytrait.html#limit()-detail.

When I am executing the above query, all the records are being returned by the dataprovider.

What's wrong with my code?

  • 写回答

2条回答 默认 最新

  • duaabhuv188411 2016-04-05 13:39
    关注

    Did some homework by myself, I find solution to the above problem by changing the code as below:

    $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);
    

    As per my scenario, I wanted to retrieve only first record. So, I used one() instead of limit(1).

    Secondly, I was returning dataProvider as $dataProvider->getModels(). I changed this to $dataProvider only. Since "ActiveDataProvider does not take care at query limit." as per Fabrizio Caldarelli's answer below (or) above, it was returning all retrieved records.

    Hope that helps someone having related issues.


    For previous code to work, you must see Fabrizio Caldarelli's answer below (or) above.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序