想要获得以下JSON输出

时间:2016-05-08 07:27:12

标签: json laravel eloquent

我有两张表如下:

quote_glass_types

id    |   name
1         clear float glass
2         Tinted glass

quote_glass_type_thickness

id    |   quote_glass_type_id_fk        |     thickness
 1                1                               5mm
 2                1                               8mm
 3                2                               5mm
 4                2                               8mm 

现在,我想加入这两个表并按如下方式获取Json:

[
{
  id:1,
  name: "clear float glass",
  thickness:{"5mm","8mm" }
 },
{ 
 id:2
 name:"tinted glass",
 thickness:{"5mm","8mm"}
 }
]

直到现在我这样做了:

$glasssetting=\DB::table('quote_glass_types')
          ->join('quote_glass_type_thickness','quote_glass_type_thickness.quote_glass_type_id_fk','=','quote_glass_types.id')
          ->select('quote_glass_type_thickness.id','name','thickness')
          ->get();

return $glasssetting;

给出了JSON,如:

[
{
"id": 1,
"name": "Clear Float Glasss",
"thickness": "5mm"
},
{
"id": 2,
"name": "Clear Float Glasss",
"thickness": "8mm"
},
{
"id": 3,
"name": "Tinted glass",
"thickness": "5mm"
 },
  {
"id": 4,
"name": "Tinted glass",
"thickness": "8mm"
  }
 ]

如何获得所需的json?

1 个答案:

答案 0 :(得分:0)

只需使用Eloquent例如

return App\QuoteGlassType::with('thickness')->get();

我不知道你的Modelname,但那就是你要找的东西。 当然,还要确保在模型中设置正确的关系。