2017-02-28 8 views
0

私は、ユーザーのカート内のアイテムのリストを持つLaravelコレクションを持っています。以下は、そのコレクションを取得するための私のコードです:製品IDをLaravel Collectionの製品名に置き換えます。

これにより
$items = Cart_Item::all(); 
$user = JWTAuth::parseToken()->toUser(); 
$items = $items->where('user_id', $user->id); 
$items = $items->map(function ($item, $key) { 
    return collect($item)->except(['user_id', 'ip_address', 'created_at', 'updated_at'])->toArray(); 
}); 

私は次のような出力が得られます。

この中に今
{ 
    "data": [ 
     { 
      "id": 1, 
      "product_id": 1, 
      "quantity": 2 
     } 
    ] 
} 

私はproductモデルを使用して、私の実際の製品名でproduct_idを交換したいとproduct_pricingモデルを使用してpriceという名前のフィールドも追加します。これどうやってするの?

答えて

1

あなたが正しく関係を設定している場合は、あなたができる:

$items = $items->map(function ($item, $key) { 
    $product = Product::with('price')->where('id', $item->product_id)->first(); 
    return [ 
    'id' => $item->id, 
    'product_id' => $item->product_id, 
    'quantity' => $item->quantity, 
    'name' => $product->name, 
    'price' => $product->price->amount, 
    ]; 
}); 

または手動の内側には道に参加:

$product = Product::select('*') 
->join('product_pricing as pp', 'pp.product_id', '=', 'product.id') 
->where('product.id', $item->product_id) 
->first(); 
+0

これはトリックをしました。ありがとう!私は私に合うように少し修正したことを意味するが、ロジックは完全に同じだった – JackSlayer94

+0

それは助けてくれる:) – SteD

関連する問題