猿问

如何修改laravel中eloquent返回的数组结构

我目前在运行 Bonus::with('users')->get() 时得到以下数组结构


我曾尝试添加数组并合并类似的键,但它不起作用。我尝试使用 laravel 中提供的辅助方法,但似乎无法使其正常工作。


[

{

"id": 1,

"users_id": 1,

"bonus_type_id": 1,

"is_paid": 0,

"amount": "100.00",

"description": "desc",

"note": null,

"created_by": 2,

"last_modified_by": null,

"created_at": null,

"updated_at": null,

"deleted_at": null,

"user": {

"id": 1,

"name": "test",

"email": "test@testing.com",

"email_verified_at": null,

"status": 1,

"created_at": "2019-07-18 11:41:35",

"updated_at": "2019-07-18 11:41:35",

"deleted_at": null

}

},

{

"id": 2,

"users_id": 1,

"bonus_type_id": 2,

"is_paid": 0,

"amount": "100.00",

"description": "desc",

"note": null,

"created_by": 2,

"last_modified_by": null,

"created_at": null,

"updated_at": null,

"deleted_at": null,

"user": {

"id": 1,

"name": "test",

"email": "test@testing.com",

"email_verified_at": null,

"status": 1,

"created_at": "2019-07-18 11:41:35",

"updated_at": "2019-07-18 11:41:35",

"deleted_at": null

}

},

{

"id": 3,

"users_id": 2,

"bonus_type_id": 2,

"is_paid": 1,

"amount": "100.00",

"description": "desc",

"note": null,

"created_by": 2,

"last_modified_by": null,

"created_at": null,

"updated_at": null,

"deleted_at": null,

"user": {

"id": 1,

"name": "another test",

"email": "another@testing.com",

"email_verified_at": null,

"status": 1,

"created_at": "2019-07-18 11:41:35",

"updated_at": "2019-07-18 11:41:35",

"deleted_at": null

}

}

]

我希望结果是这样的


[

  {

    user_id: 1,

    name: "test",

    bonuses: [

      {

        bonus_type_id: 1,

        amount: 100,

        is_paid: 0,

      },

      {

        bonus_type_id: 2,

        amount: 100,

        is_paid: 0,

      }

    ],

  },

  {

    user_id: 2,

    name: "another",

    bonuses: [

      {

        bonus_type_id: 2,

        amount: 100,

        is_paid: 1,

      },

    ]

  }

]


翻翻过去那场雪
浏览 108回答 2
2回答

POPMUISE

你需要改变你雄辩的关系。在模型内部为奖金表定义hasMany关系函数并使用它来获得所需的结果,如下所示:bonusesUserUser::with('bonuses')->get();这样它将从用户表返回结果并为每个用户填充奖金。说得通?

白衣染霜花

您可以使用 select 子查询获取特定信息,如果您的关系设置正确,这应该可以工作。User::select('user_id','name','bonus_id')    ->with(array('bonuses'=> function($query){         $query->select('bonus_type_id','amount','is_paid');    }))->get();
随时随地看视频慕课网APP
我要回答