从查询 laravel obj['pivot'] 中移除 obj

问题描述

我的查询,我正在使用 laravel 权限 spatie。因为我需要显示它会返回相同格式的数据。并且不需要显示枢轴。 如果你看到,支点是员工->用户->角色->支点

public function index()
{
    $resp = Employes::where('estado',1)
    ->with('user.roles:id,name')
    ->get();

    return  response()->json($resp);
}

回复

 [
   {
      "employ":"Juan","age":21,"user":{
         "id":5,"name":"mario maradionio","email":"empleado@gmail.com","tipo_usuario":null,"roles":[
            {
               "id":1,"name":"root","pivot":{
                  "model_id":5,"role_id":1,"model_type":"App\\User"
               }
            },{
               "id":2,"name":"Alumno","role_id":2,{
               "id":3,"name":"Encargado","role_id":3,"model_type":"App\\User"
               }
            }
         ]
      }
   ]

模型 使用 Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable
{   
    use Notifiable;
    use HasRoles;
}

使用集合不显示角色,只显示一个角色,角色名称为空

[
            'id'         => $this->id,'employe'       => $this->name,'user' => [
               'id' => $this->id,'name' => $this->name,'roles' => [
                    'id' => $this->id,'name' => $this->name
               ]
            ]
        ];

解决方法

在您的 Role.php 模型中添加隐藏属性

创建一个 Role.php 并扩展然后 Spatie\Permission\Models\Role

<?php

namespace App\Models;

use Spatie\Permission\Models\Role as BaseRole;

class Role extends BaseRole
{
    use HasFactory;

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'pivot'
    ];

}

参考链接 https://laravel.com/docs/8.x/eloquent-serialization#hiding-attributes-from-json

,

您应该创建一个 Resource 类并返回它。

public function index()
{
    $employees = Employes::where('estado',1)
        ->with('user.roles')
        ->get();

    return EmployeeResource::collection($employees);
}

您可以参考创建资源的文档:https://laravel.com/docs/8.x/eloquent-resources

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...