【问题标题】:How to disable or remove updated_At and Created_at when returning data返回数据时如何禁用或删除 updated_At 和 Created_at
【发布时间】:2020-04-08 00:57:25
【问题描述】:

我试图在返回对 api 的响应之前删除 created_at 和 updated_at 。我想从 Place_Type 和 Places 中删除这些字段 我怎样才能做到这一点? : 我试过了:unset(placetypes) 但没用

这是我的代码:

    public function places()
    {

        $placeType = PlaceType::with('places')->where('id', 1)->get();

        return response()->json(['placeType' => $placeType]);
    }

请求结果:

 "placeType": [
        {
            "id": 1,
            "name": "Moriah O'Conner",
            "icon": "https://picsum.photos/200/300",
            "status": 1,
            "created_at": "2019-12-14 18:23:19",
            "updated_at": "2019-12-14 18:23:19",
            "places": [
                {
                    "id": 1,
                    "name": "Linda Leffler",
                    "description": "Alice's shoulder, and it set to work, and very soon came to ME, and told me he was in the air. She did it so VERY remarkable in that; nor did Alice think it would feel very queer to ME.' 'You!' said.",
                    "icon": "https://picsum.photos/200/300",
                    "image_name": "https://picsum.photos/200/300",
                    "rating": 2,
                    "longitude": -53.389979,
                    "latitude": 19.633458,
                    "availability": 1,
                    "status": 1,
                    "place_type_id": 1,
                    "created_at": "2019-12-14 18:23:19",
                    "updated_at": "2019-12-14 18:23:19"
                },
                {
                    "id": 2,
                    "name": "Lauren Cartwright",
                    "description": "I should say \"With what porpoise?\"' 'Don't you mean by that?' said the King. 'I can't remember half of anger, and tried to look at it!' This speech caused a remarkable sensation among the leaves.",
                    "icon": "https://picsum.photos/200/300",
                    "image_name": "https://picsum.photos/200/300",
                    "rating": 1,
                    "longitude": -38.117034,
                    "latitude": -32.248637,
                    "availability": 1,
                    "status": 1,
                    "place_type_id": 1,
                    "created_at": "2019-12-14 18:23:19",
                    "updated_at": "2019-12-14 18:23:19"
                }...,
               }

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    将字段添加到$hidden 数组中:

    // Model
    
    protected $hidden = ['created_at', 'updated_at'];
    

    【讨论】:

    • 这必须适用于任何模型查询。请在placeTypeplaces 模型中使用protected $hidden = ['created_at', 'updated_at'];
    【解决方案2】:

    您可以使用不同的方法。

    方法一:只从数据库中获取必填字段

    您可以使用select() 方法从数据库中仅检索必填字段。因此,您可以省略不必要的字段。

    $placeType = PlaceType::with(['places'  => function ($query) {
                        $query->select('id', 'name', 'description', 'icon',
                            'image_name', 'rating', 'longitude', 'latitude',
                            'availability', 'status', 'place_type_id'); //timestamps excluded
                    }])
                    ->select('id', 'name', 'icon', 'status') //timestamps excluded
                    ->where('id', 1)
                    ->get();
    
    return response()->json(['placeType' => $placeType]);
    
    

    此代码将仅输出父模型 (placetype) 和子模型 (places) 中的指定字段。

    如果您多次使用这些自定义选择查询并且多次写入所有字段名称很困难,那么您可以使用如下模型范围。

    PlaceType 模型

    // add all columns from your table
    protected $columns = ['id', 'name', 'icon', 'status', 'created_at', 'updated_at'];
    
    public function scopeExclude($query,$value=[]) 
    {
        return $query->select( array_diff( $this->columns,(array) $value) );
    }
    

    放置模型

    // add all columns from your table
    protected $columns = ['id', 'name', 'description', 'icon', 'image_name',
                            'rating', 'longitude', 'latitude', 'availability',
                            'status', 'place_type_id', 'created_at', 'updated_at'
                        ];
    
    public function scopeExclude($query,$value=[]) 
    {
        return $query->select( array_diff( $this->columns,(array) $value) );
    }
    

    然后您可以删除不需要的字段,如下所示

    $placeType = PlaceType::with(['places' => function ($query) {
                        $query->exclude(['created_at', 'updated_at']); //exclude fields from Place model
                    }])
                    ->exclude(['created_at', 'updated_at']) //exclude fields from PlaceType model
                    ->where('id', 1)
                    ->get();
    

    礼貌:This 所以@Razor 的回答

    方法 2:在您需要的地方隐藏您的列以防止序列化

    您可以使用 laravel 的 makeHidden() 方法隐藏您的列以防止序列化。在此方法中,在获取包含所有字段的行后,您将指定的字段设为隐藏。 [请注意,排除的变量不会出现在 json 上,但可能会在转储上显示]。

    //get rows with all fileds (except hidden)
    $placeType = PlaceType::with('places')->where('id', 1)->get();
    //making timestamps hidden in child model's rows
    $placeType->places->makeHidden(['created_at','updated_at']);
    //making timestamps hidden in parent model's rows
    $placeType->makeHidden(['created_at','updated_at']);
    
    return response()->json($placeType);
    

    礼貌:This@sajed 的回答

    方法3:使用隐藏属性

    如果应用程序中大部分时间不需要时间戳,您可以使用模型的hidden 属性。

    PlaceType 模型 & Place 模型

    protected $hidden = ['created_at', 'updated_at'];
    

    希望这会有所帮助。 ?

    【讨论】:

      【解决方案3】:

      1) 你只需要在你想隐藏它的每个模型中声明public $timestamps = false;

      2) 您还可以通过从迁移中删除 $table->timestamps() 来禁用时间戳。

      3) 在你的模型中声明protected $hidden = ['created_at', 'updated_at'];

      【讨论】:

      • 我这样做了,但它仍然返回 updated_at 和 created_at
      • Place_TypePlaces@Developer 模型中执行此操作
      • 如果需要它们但不想显示它们,请将它们设置在模型中的 $hidden 中。 protected $hidden = ['created_at', 'updated_at'];@开发者
      【解决方案4】:

      如果您想从模型中删除时间戳,如前所述,请将其放在您的模型中:

      public $timestamps = false;
      
      

      同时在 up() 方法中使用以下代码创建迁移并运行它:

      Schema::table('your_table', function (Blueprint $table) {
          $table->dropTimestamps();
      });
      

      您可以在 down() 方法中使用 $table->timestamps() 来允许回滚。 或在模型中

      const UPDATED_AT = null;
      const CREATED_AT = null;
      

      【讨论】:

        【解决方案5】:

        假设 $placeType 是数组,你可以使用这个递归函数:

        function removeTimeStampValues($array) 
        {
            if(array_key_exists('created_at', $array) && array_key_exists('updated_at', $array)) {
               unset($array['created_at']);
               unset($array['updated_at']);
        
            }
            foreach ($array as $key => $value) {
               if(is_array($value)) {
                 $array[$key] = recursiveRemoveTimeStampValue($value);
               }
            }
        
            return $array;
        }
        

        【讨论】:

          【解决方案6】:

          如果您不想要这些列,您可以根据documentation(在“时间戳”标题下)按照其他人所说的那样做。

          但是如果您需要这些列并且不希望它们出现在 json 响应中,您可以使用resource。请参阅documentation

          【讨论】:

            猜你喜欢
            • 2014-01-16
            • 2020-03-28
            • 2015-09-16
            • 1970-01-01
            • 1970-01-01
            • 2018-04-24
            • 2017-05-26
            • 1970-01-01
            • 2011-06-11
            相关资源
            最近更新 更多