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条)

报告相同问题?

悬赏问题

  • ¥30 win c++ socket
  • ¥15 CanMv K210开发板实现功能
  • ¥15 C# datagridview 栏位进度
  • ¥15 vue3页面el-table页面数据过多
  • ¥100 vue3中融入gRPC-web
  • ¥15 kali环境运行volatility分析android内存文件,缺profile
  • ¥15 写uniapp时遇到的问题
  • ¥15 vs 2008 安装遇到问题
  • ¥15 matlab有限元法求解梁带有若干弹簧质量系统的固有频率
  • ¥15 找一个网络防御专家,外包的