I have a query that I make to obtain the users, this table is related to 3 others, but the query is a bit long, I would like to handle the JsonResource but I have not been able to generate the JsonResource as I have it in the normal query.
Method index:
public function index()
{
$users = User::select('users.id', 'users.name', 'users.email', 'users.username', 'users.status', 'users.id_cost_center', 'cost_centers.code AS code_cost_center', 'cost_centers.description AS cost_center',
'users.id_dependence', 'dependencies.description AS dependence', 'users.id_profile', 'profiles.name AS profile', 'users.created_at')
->join('cost_centers', 'users.id_cost_center', '=', 'cost_centers.id')
->join('dependencies', 'users.id_dependence', '=', 'dependencies.id')
->join('profiles', 'users.id_profile', '=', 'profiles.id')
->orderBy('users.created_at', 'desc')
->get();
$message = $this->sendResponse($users, 'List of users');
return $message;
}
Relationships in my user model:
public function cost_center()
{
return $this->belongsTo(CostCenter::class, 'id_cost_center');
}
public function dependence()
{
return $this->belongsTo(Dependence::class, 'id_dependence');
}
public function profile() {
return $this->belongsTo(Profile::class, 'id_profile');
}
Relationships in the other tables:
CostCenter:
public function users()
{
return $this->hasMany(User::class, 'id_cost_center');
}
Dependence:
public function users()
{
return $this->hasMany(User::class, 'id_dependence');
}
Profile:
public function users()
{
return $this->hasMany(User::class, 'id_profile');
}
Response:
{
"success": true,
"data": [
{
"id": 1,
"name": "admin",
"email": "[email protected]",
"username": "admin",
"status": 1,
"id_cost_center": 1,
"code_cost_center": "001",
"cost_center": "Admin",
"id_dependence": 1,
"dependence": "System",
"id_profile": 1,
"profile": "Developer",
"created_at": "2021-09-13T11:26:46.000000Z"
},
{
"id": 2,
"name": "user",
"email": "[email protected]",
"username": "user",
"status": 1,
"id_cost_center": 2,
"code_cost_center": "002",
"cost_center": "Service",
"id_dependence": 2,
"dependence": "Store",
"id_profile": 2,
"profile": "Aux",
"created_at": "2021-09-13T11:26:46.000000Z"
}
],
"message": "List of users"
}
I have tried to create a user collection class but it only generates the users but not the relations:
public function toArray($request)
{
return [
'data' => $this->collection,
];
}
It only shows me the user data, I would like to be able to get the same answer that I get in the first normal query.