返回数据时如何禁用或删除updated_At和Created_at

时间:2019-12-15 06:48:15

标签: php laravel

我正在尝试在将响应返回给api之前删除created_at和updated_at。我想从 Place_Type和位置中删除这些字段 我怎样才能做到这一点? : 我尝试过: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"
                }...,
               }

7 个答案:

答案 0 :(得分:2)

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

// Model

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

答案 1 :(得分:1)

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

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

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

答案 2 :(得分:1)

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

public $timestamps = false;

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

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

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

const UPDATED_AT = null;
const CREATED_AT = null;

答案 3 :(得分:1)

假设$ 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;
}

答案 4 :(得分:1)

您可以使用多种方法。

方法1:仅从数据库中获取必填字段

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

$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)中的指定字段。

如果您多次使用这些自定义的select查询,并且很难多次写入所有字段名称,则可以使用如下所示的模型作用域。

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'];

希望这会有所帮助。 ?

答案 5 :(得分:0)

在您的PlaceType模型中使用public $timestamps = false;

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class PlaceType extends Model
{
    public $timestamps = false;

    //
}

或尝试

class PlaceType extends Model
{
    /**
     * The name of the "updated at" column.
     *
     * @var string
     */
    const UPDATED_AT = null;
}

public function setUpdatedAt($value)
{
    // Do nothing.
}

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

答案 6 :(得分:0)

如果您不希望使用这些列,则可以按照documentation(在“时间戳记”标题下)进行操作。

但是,如果您需要这些列并且只是不想在json响应中使用它们,则可以使用resource。参见documentation