简体   繁体   中英

How to modify array structure returned by eloquent in laravel

I currently have the below array structure that I get when running Bonus::with('users')->get()

I have tried adding the array and merging similar keys but it is not working. I tried using the helper methods provided in laravel but I don't seem to be able to get it working.

[
{
"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
}
}
]

I want the result to be something like that

[
  {
    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,
      },
    ]
  }
]

You need to change your eloquent relationship. Define hasMany relationship function bonuses inside User model for bonuses table and use that to get the desired result like so:

User::with('bonuses')->get();

That way it will return results from users table and populate bonuses for each user.

makes sense?

You can get specific information with select subquery, if your relations are correctly set, this should work.

User::select('user_id','name','bonus_id')
    ->with(array('bonuses'=> function($query){
         $query->select('bonus_type_id','amount','is_paid');
    }))->get();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM