2017-01-10 5 views
0

JSONファイルでバックエンドからフロントエンドにデータを渡したいが、キーと値として関連付けを返す代わりに、テーブルから余分なフィールドを返す。JSONファイルが追加フィールド付きの連想配列を返す

余分なフィールドを非表示にすることができますか?

namespace App\Http\Controllers; 
use App\Notification; 
use App\Status; 

use Illuminate\Http\Request; 

class ChartController extends Controller 
{ 
    public function speedHistory($notification_id){ 

     $o_notification = Notification::find(intval($notification_id)); 
     $o_status = Status::where('name','speed')->first(); 

     $o_response = $o_notification->statuses()->where('status_id', $o_status->id) 
     ->select('values AS value', 'created_at AS timestamp')->orderBy('created_at','DESC')->get(); 

     if($o_response){ 
      return response()->json($o_response->toArray()); 
     }else{ 
      // return an empty json array instead of false 
      //return false; 
      return response()->json(array()); 
     } 
    } 
} 

このような復帰は、私はこの場合72とタイムスタンプの値を得ることを期待していました。あなただけが必要な鍵を取得するためにonly functionを使用できるように

[{"value":"72","pivot":{"notification_id":1,"status_id":2,"values":"72","created_at":"2017-01-10 12:48:29","updated_at":"2017-01-10 12:48:29"}}] 

答えて

0

これは、あなたが望む結果を得る方法をされています

$o_response = $o_notification->statuses()->where('status_id', $o_status->id) 
    ->orderBy('created_at','DESC') 
    ->get() 
    ->transform(function ($item, $key) { 
     return collect([ 
      'values' => $item->pivot->values, 
      'created_at' => $item->pivot->created_at 
     ]); 
    }); 

をそれからちょうど彼はそう、これはしませんピボット列の「価値」と「created_atとを」持っている

return response()->json($o_response); 
+0

私はコレクションの代わりにアソシエイティブな配列を私に返してくれるのかと尋ねるでしょう。これは私が得るものです。 [{"value": "72"、 "created_at": "2017-01-10 12:48:29"}] –

+0

コレクションのコレクションを返すはずです(配列をコレクションに変換しました) ( 'collect([values])'を参照してください)、コレクションの便利なヘルパーを利用することができます。あなたが投稿した結果は、見つかったすべての値の配列に過ぎません。 - > idを通知に追加すると、結果が配列に追加されます。 – devk

0

関係は、Laravel Collectionを返します。そのよう

$o_response = $o_notification->statuses() 
    ->where('status_id', $o_status->id) 
    ->select('values AS value', 'created_at AS timestamp') 
    ->orderBy('created_at', 'DESC') 
    ->get() 
    ->only(['value', 'created_at']); 

更新:

セット内に複数の結果がある場合は、上記の答えは動作しません。この場合、the map functionを使用できます。

$o_response = $o_notification->statuses() 
    ->where('status_id', $o_status->id) 
    ->select('values AS value', 'created_at AS timestamp') 
    ->orderBy('created_at','DESC') 
    ->get() 
    ->map(function ($v) { 
     return [ 
      'value' => $v->value, 
      'created_at' => $v->created_at 
     ]; 
    }); 
+0

を返しますそのままで作業してください。 – devk

+0

代わりに空の配列を返します。 –

+0

私は自分の答えを更新して、マッピング機能で解決策を試してみてください。 – Jerodev