使用数据库中的值生成对象数组

时间:2018-07-18 13:34:37

标签: php laravel

假设我有这张桌子:

id    |    product_item    |    head_count
1     |         400        |        2
2     |         401        |        5

所需的输出:

[
   {"product_item": 400,"head_count": 2},
   {"product_item": 401,"head_count": 5}
]

如何使用Laravel或Eloquent取得所需的输出?

4 个答案:

答案 0 :(得分:3)

Follow bellow step  
(1) declare in your controller **use DB**  

(2) write Query:  
$product = DB::table('tablename')->select('col1','col2')->get(); 

(3)dd($product); OR print_r($product);  

You got the result in $product  

echo json_encode($product); 

OR if you are load your view then,  
return view('VIEW_NAME',compact('product'));  

OR return like this and got the result on your view file.

return response()->json($product);

I hope its help.

答案 1 :(得分:0)

(例如)为表创建模型Product,然后选择数据:

Product::get(["product_item","head_count"]);

这将返回产品对象的集合。

[ 
    {
        "product_item": 400,
        "head_count": 2
    },
    {
        "product_item": 401,
        "head_count": 5
    }
]

注意::如果您的表名是products,则无需将表名添加到模型中,因为Product是表的单数名称,这表示您遵循约定,laravel会自动检测相关表。

否则,您需要在表Product.php的顶部添加表名,例如:

class Product extends Model
{

    protected $table = 'products';

}

答案 2 :(得分:0)

尝试一下:

$products = App\Product::select('product_item', 'head_count')->get()->toArray();

或者如果是一个:

$product = App\Product::select('product_item', 'head_count')->first()->toArray();

    $product = App\Product::get(['product_item', 'head_count'])->toArray();

并返回:

[ {Producto}, {Producto}]

答案 3 :(得分:0)

您可以尝试这种方式:

$products = Products::all();

$data = [];

foreach($products as $value)
{
   $temp = [
      'product_item' => $value->product_item,
      'head_count' => $value->head_count
   ];

   array_push($data,$temp);
}

return $data;

OR

return response()->json($data);

您将在$ data中获得所需的输出