【问题标题】:JSON data from two tables without repeating joined table primary key来自两个表的 JSON 数据,没有重复连接的表主键
【发布时间】:2017-05-30 00:24:12
【问题描述】:

我有两个模型:

Category 型号有:id PRIMARY_KEYcategory_name...

Item 模型有:id PRIMARY_KEYitem_namecategory_id(在类别表上是 id)、...

我希望实现这个 JSON 响应:

Item:
{
    "id": 1,
    "item_name": "some item name",
    "category": {
        "id": "5",
        "category_name": "some category name"
    }
}

到目前为止,我已经设法实现了唯一的响应:

{
    "id": 1,
    "item_name": "some item name",
    "category_id": "5", // i dont want it to appear here!
    "category": {
        "id": "5",
        "category_name": "some category name"
    }
}

有查询:

$data = Item::select('id', 'item_name', 'category_id')->with(['category' => function ($query) {
            $query->select('id', 'category_name');
        }])->get();
return response()->json($data);

我尝试了select('id', 'item_name') 而不是select('id', 'item_name', 'category_id'),但它失败了,因为它需要'category_id' 才能使with 工作。有什么干净的解决方案吗?

【问题讨论】:

    标签: php laravel laravel-5.2


    【解决方案1】:

    是的,您不能删除 category_id,因为它是创建关系所必需的。您可以在查询并设置$data 后执行类似的操作。

    $response = [];
    $data->each(function ($value) use (&$response) { // pass $response by reference
        unset($value->category_id);
        $response[] = $value;
    });
    return response()->json($response);
    

    【讨论】:

      【解决方案2】:

      解决办法是把hidden改成Collection

      $data = Item::select('id', 'item_name', 'category_id')->with(['category' =>     function ($query) {
                  $query->select('id', 'category_name');
              }])->get()->makeHidden('category_id');
      return response()->json($data);
      

      【讨论】:

        猜你喜欢
        • 2012-09-17
        • 2021-04-08
        • 2014-08-04
        • 1970-01-01
        • 2021-03-08
        • 2017-01-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多