在Laravel Select查询中获取其他数据

时间:2019-06-19 09:31:27

标签: php laravel select eloquent

当我在laravel中使用选择查询时,会得到其他数据。

我的查询

MyModal::where('state', 1)
        ->select('code as popupContent', 'latitude as lat','longitude as lng')
        ->take(3)
        ->get()
        ->toArray();

返回的数据:

[
  [
    "popupContent" => "260563"
    "lat" => 35.765014
    "lng" => 51.333209
    "update_time" => null
    "rooms_number" => null
  ]
  [
    "popupContent" => "891962"
    "lat" => 35.794741
    "lng" => 51.391965
    "update_time" => null
    "rooms_number" => null
  ]
  [
    "popupContent" => "477845"
    "lat" => 35.723649
    "lng" => 51.320682
    "update_time" => null
    "rooms_number" => null
  ]
]

在上面的代码中,添加了字段update_timerooms_number

我想提供此数据:

[
  [
    "popupContent" => "260563"
    "lat" => 35.765014
    "lng" => 51.333209
  ]
  [
    "popupContent" => "891962"
    "lat" => 35.794741
    "lng" => 51.391965
  [
    "popupContent" => "477845"
    "lat" => 35.723649
    "lng" => 51.320682
  ]
]

3 个答案:

答案 0 :(得分:1)

您可能会覆盖$append属性

public $appends = ['update_time', 'rooms_number'];

对于隐藏的附加列,请使用此

MyModal::where('state', 1)
    ->select('code as popupContent', 'latitude as lat','longitude as lng')
    ->take(3)
    ->get()
    ->makeHidden(['update_time', 'rooms_number'])
    ->toArray();

答案 1 :(得分:1)

我认为它仍在您的模型中。 您可以尝试:

$items =  DB::table('tableName')
->where('state', 1)
->select('code as popupContent', 'latitude as lat','longitude as lng')
->take(3)->get();

答案 2 :(得分:-1)

您可以使用以下代码:

    YourModel::select('code as popupContent', 'latitude as lat','longitude as lng')
    ->where('state', 1)
    ->take(3)
    ->get()
    ->toArray();