2017-04-03 79 views
0

如何從數據庫中獲取模型,然後使用with語句將其轉換爲包含額外信息的數組。將模型轉換爲數組並返回爲json

public function edit($id) { 
    // convert product to array; 
    $product = Product::findOrFail($id)->with('supplier', 'category'); 

    $data = [ 
     'suppliers' => Supplier::all()->pluck('company', 'id'), 
    ];   

    // cannot merge because $product is object and cannot turn into array 
    // the only way I know to convert to array is doing this 
    // $product->first()->toArray() but this gets the first item in the database 
    $product = array_merge($product, $data); 

    return response()->json($product, 200, ['Content-Length' => strlen(json_encode($product))]); 
} 

回答

1

你可以使用Laravel的收集幫助,使之簡單:

collect($product)->toArray() 

那麼你應該能夠做到:

$product array_merge(collect($product)->toArray(), $data); 
0

這個怎麼樣:

$return = [ 
    'suppliers' => Supplier::all()->pluck('company', 'id'), 
    'product' => $product // or $product->toArray() 
]; 

return response()->json($return, 200); 

如果你需要供應商產品屬性,你可以試試這個:

$productArr = $product->toArray(); 
$productArr['suppliers'] = Supplier::all()->pluck('company', 'id'); 

return response()->json($productArr, 200);