【问题标题】:How to get data from SQL in laravel using whereIn and take function?如何使用 whereIn 和 take 函数从 laravel 中的 SQL 获取数据?
【发布时间】:2020-04-03 22:24:12
【问题描述】:

如何获取数组中每个值的数据。 我只想要两个值的 1 个结果。

$userBikes = array('862549040389788','12345');


$data = DB::table('geolocation')
->whereIn('Imei',$userBikes)
->take(1)      
->get();

结果:

["28.537857", "77.269325", "862549040389788"]

但我期待这个结果:

["28.537857", "77.269325", "862549040389788"]
["28.537857", "77.269325", "12345"]

【问题讨论】:

  • 不太清楚,你到底想要什么?其中之一?
  • 我想要一个来自“862549040389788”的值和一个来自“12345”的值现在清楚了吗?
  • 但我只从“862549040389788”中获得价值
  • 你的意思是一个记录包括两个值吗?
  • 等我告诉你结果我得到了什么和我想要什么

标签: php mysql laravel


【解决方案1】:

根据您的 cmets,我认为您需要按查询分组。

$userBikes = array('862549040389788','12345');

$data = DB::table('geolocation')
->whereIn('Imei', $userBikes)
->groupBy('Imei')
->selectRaw('any_value(id) as id, any_value(Lat) as Lat, any_value(Lng) as Lng, any_value(created_at) as created_at, Imei')
->get();

【讨论】:

  • 嘿,我可以用这个获取最新记录吗?
  • 使用 max 代替 any_value ->selectRaw('any_value(lat) as lat, any_value(lon) as lon, max(created_at) as created_at, Imei')
  • 每个(数组)值只返回一条记录。如果我想分别返回两条记录怎么办?
【解决方案2】:

如果您希望 $userBikes 数组中的每个元素都有 1 个值,则需要进行 2 个不同的查询。

$userBikes = array('862549040389788','12345');
$output = array();


foreach($userBikes as $imei) { 
    $data = DB::table('geolocation')
       ->where('Imei',$imei)
       ->take(1)      
       ->get()->toArray();
    array_push($output, $data)
return $output;

第二种解决方案是从查询中删除take(1),并从数据对象中过滤每个值。

【讨论】:

  • 这是唯一的解决方案
  • @Gaurav 可能是的。
  • @Gaurav 是的,它是唯一的一个。 Database/Eloquent 只返回简单的集合/数组,而不是多维的。但是这个答案不是最好的。因为这将创建与 $userBike 数组中的项目一样多的数据库请求。最好将 Diogos answer 和 foreach 结合起来。
  • @gaurav wherein 替换为 where
【解决方案3】:

您必须从查询中删除take(1)

Take(1) 会将结果限制为 1 行。

应该是这样的:

$data = DB::table('geolocation')
->whereIn('Imei',$userBikes)      
->get();

【讨论】:

    猜你喜欢
    • 2020-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-11
    • 2015-04-28
    • 1970-01-01
    • 2016-07-18
    相关资源
    最近更新 更多