Отменить установку всех полей, кроме известных полей в Laravel? - PullRequest
0 голосов
/ 06 августа 2020

Я хочу отключить все поля документа, кроме известного, например, в данном документе я хочу сохранить только три поля, такие как

_id, created_at и updated_at

в приведенном ниже примере документа

{
"_id" : ObjectId("5c714985c6f0fc14656c7042"),
"email" : "test@gmail.com",
"name" : "Test",
"password" : "$2y$10$Ye3E2C64RmcqXUtMwI50gucuwxJxhU4cniNCg/ZR8ramJ6o81iIN.",
"is_social" : 1,
"device_id" : null,
"role" : "User",
"latlng" : {
    "type" : "Point",
    "coordinates" : [ 
        -73.2113104427108, 
        44.4808123190551
    ]
},
"logout" : 0,
"isActive" : 1,
"sendNotifications" : 1,
"isAllowedOnce" : 0,
"atoken" : "ryemRzfCOYGQ88fP",
"updated_at" : ISODate("2020-08-07T07:55:45.000Z"),
"created_at" : ISODate("2019-02-23T13:24:21.000Z"),
"city" : "Burlington",
"country" : "United States",
"state" : "Vermont",
"no_of_sent_halohas" : 209,
"logInOutTime" : ISODate("2020-08-07T07:55:45.000Z"),
"ptoken" : null,

"deliveredNotification" : 1,
"reminderNotification" : 1,
"offset" : -4,
"display_remindertime" : "11:00 AM",
"remindertime" : 1500,
"suppressReactionInstruction" : true,
"no_of_reported_received" : 1,
"reported_halohas_received" : [ 
    "5cd1ec01c6f0fc109b7f1ee3"
],
"no_of_strike_received" : 1,
"strike_received_halohas" : [ 
    "5cd1ec01c6f0fc109b7f1ee3"
],
"halohaFetchTimeStamp" : ISODate("2019-07-29T00:52:00.000Z"),
"no_of_reported_created" : 5,
"reported_halohas" : [ 
    "5d3af62ac6f0fc5655571335", 
    "5d42d7f4c6f0fc1740726a29", 
    "5d866280c6f0fc61471ea41f", 
    "5d90fcf0c6f0fc4a3d153a6e", 
    "5df8df89c6f0fc558939c92e"
],
"halohaFetchId" : "5f1c8f68eaead87aa274fc12",
"confetti_counter" : 6,
"location_settings" : {
    "showCity" : 1,
    "showState" : 1,
    "showCountry" : 1
},
"sendConfettiOn" : 213,
"share_app_time" : 2200,
"notified_on_three_halohas" : true,
"reaction_phrases" : [ 
    1, 
    2, 
    1, 
    1, 
    2, 
    0, 
    0, 
    0
]

}

документ может иметь больше полей, чем указанные выше документы, короче говоря, я не знаю, какие и сколько полей имеют документы.

Это данные dd ($ user), которые я получаю после find ($ id)

^ App\Models\User {#135
  #table: "users"
  #primaryKey: "_id"
  #dates: array:4 [
    0 => "created_at"
    1 => "updated_at"
    2 => "logInOutTime"
    3 => "halohaFetchTimeStamp"
  ]
  #fillable: array:29 [
    0 => "_id"
    1 => "name"
    2 => "email"
    3 => "password"
    4 => "latlng"
    5 => "is_social"
    6 => "no_of_strike_received"
    7 => "no_of_strike_created"
    8 => "no_of_reported_received"
    9 => "no_of_reported_created"
    10 => "no_of_sent_halohas"
    11 => "no_of_suggested_halohas"
    12 => "confetti_counter"
    13 => "strike_received_halohas"
    14 => "strike_made_halohas"
    15 => "reported_halohas"
    16 => "reported_halohas_received"
    17 => "suggested_halohas"
    18 => "no_black_list_warning"
    19 => "used_black_list_words"
    20 => "location"
    21 => "state"
    22 => "city"
    23 => "country"
    24 => "device_id"
    25 => "beta_permission"
    26 => "suppressReactionInstruction"
    27 => "location_settings"
    28 => "share_app_time"
  ]
  #dateFormat: "m/d/Y"
  #hidden: array:1 [
    0 => "password"
  ]
  +encryptable: array:3 [
    0 => "user_email"
    1 => "first_name"
    2 => "last_name"
  ]
  #collection: null
  #parentRelation: null
  #connection: "mongodb"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #attributes: array:44 [
    "_id" => MongoDB\BSON\ObjectId {#119
      +"oid": "5c714985c6f0fc14656c7042"
    }
    "email" => "test@gmail.com"
    "name" => "Test"
    "password" => "$2y$10$Ye3E2C64RmcqXUtMwI50gucuwxJxhU4cniNCg/ZR8ramJ6o81iIN."
    "is_social" => 1
    "device_id" => null
    "role" => "User"
    "latlng" => array:2 [
      "type" => "Point"
      "coordinates" => array:2 [
        0 => -73.211310442711
        1 => 44.480812319055
      ]
    ]
    "logout" => 0
    "isActive" => 1
    "sendNotifications" => 1
    "isAllowedOnce" => 0
    "atoken" => "ryemRzfCOYGQ88fP"
    "updated_at" => MongoDB\BSON\UTCDateTime {#122
      +"milliseconds": "1596786945000"
    }
    "created_at" => MongoDB\BSON\UTCDateTime {#120
      +"milliseconds": "1550928261000"
    }
    "city" => "Burlington"
    "country" => "United States"
    "state" => "Vermont"
    "no_of_sent_halohas" => 209
    "logInOutTime" => MongoDB\BSON\UTCDateTime {#129
      +"milliseconds": "1596786945000"
    }
    "ptoken" => null

    "deliveredNotification" => 1
    "reminderNotification" => 1
    "offset" => -4
    "display_remindertime" => "11:00 AM"
    "remindertime" => 1500
    "suppressReactionInstruction" => true
    "no_of_reported_received" => 1
    "reported_halohas_received" => array:1 [
      0 => "5cd1ec01c6f0fc109b7f1ee3"
    ]
    "no_of_strike_received" => 1
    "strike_received_halohas" => array:1 [
      0 => "5cd1ec01c6f0fc109b7f1ee3"
    ]
    "halohaFetchTimeStamp" => MongoDB\BSON\UTCDateTime {#124
      +"milliseconds": "1564361520000"
    }
    "no_of_reported_created" => 5
    "reported_halohas" => array:5 [
      0 => "5d3af62ac6f0fc5655571335"
      1 => "5d42d7f4c6f0fc1740726a29"
      2 => "5d866280c6f0fc61471ea41f"
      3 => "5d90fcf0c6f0fc4a3d153a6e"
      4 => "5df8df89c6f0fc558939c92e"
    ]
    "halohaFetchId" => "5f1c8f68eaead87aa274fc12"
    "confetti_counter" => 6
    "location_settings" => array:3 [
      "showCity" => 1
      "showState" => 1
      "showCountry" => 1
    ]
    "sendConfettiOn" => 213
    "share_app_time" => 2200
    "notified_on_three_halohas" => true
    "reaction_phrases" => array:8 [
      0 => 1
      1 => 2
      2 => 1
      3 => 1
      4 => 2
      5 => 0
      6 => 0
      7 => 0
    ]
  ]
  #original: array:44 [
    "_id" => MongoDB\BSON\ObjectId {#119}
    "email" => "test@gmail.com"
    "name" => "Test"
    "password" => "$2y$10$Ye3E2C64RmcqXUtMwI50gucuwxJxhU4cniNCg/ZR8ramJ6o81iIN."
    "is_social" => 1
    "device_id" => null
    "role" => "User"
    "latlng" => array:2 [
      "type" => "Point"
      "coordinates" => array:2 [
        0 => -73.211310442711
        1 => 44.480812319055
      ]
    ]
    "logout" => 0
    "isActive" => 1
    "sendNotifications" => 1
    "isAllowedOnce" => 0
    "atoken" => "ryemRzfCOYGQ88fP"
    "updated_at" => MongoDB\BSON\UTCDateTime {#122}
    "created_at" => MongoDB\BSON\UTCDateTime {#120}
    "city" => "Burlington"
    "country" => "United States"
    "state" => "Vermont"
    "no_of_sent_halohas" => 209
    "logInOutTime" => MongoDB\BSON\UTCDateTime {#129}
    "ptoken" => null
    "deliveredNotification" => 1
    "reminderNotification" => 1
    "offset" => -4
    "display_remindertime" => "11:00 AM"
    "remindertime" => 1500
    "suppressReactionInstruction" => true
    "no_of_reported_received" => 1
    "reported_halohas_received" => array:1 [
      0 => "5cd1ec01c6f0fc109b7f1ee3"
    ]
    "no_of_strike_received" => 1
    "strike_received_halohas" => array:1 [
      0 => "5cd1ec01c6f0fc109b7f1ee3"
    ]
    "halohaFetchTimeStamp" => MongoDB\BSON\UTCDateTime {#124}
    "no_of_reported_created" => 5
    "reported_halohas" => array:5 [
      0 => "5d3af62ac6f0fc5655571335"
      1 => "5d42d7f4c6f0fc1740726a29"
      2 => "5d866280c6f0fc61471ea41f"
      3 => "5d90fcf0c6f0fc4a3d153a6e"
      4 => "5df8df89c6f0fc558939c92e"
    ]
    "halohaFetchId" => "5f1c8f68eaead87aa274fc12"
    "confetti_counter" => 6
    "location_settings" => array:3 [
      "showCity" => 1
      "showState" => 1
      "showCountry" => 1
    ]
    "sendConfettiOn" => 213
    "share_app_time" => 2200
    "notified_on_three_halohas" => true
    "reaction_phrases" => array:8 [
      0 => 1
      1 => 2
      2 => 1
      3 => 1
      4 => 2
      5 => 0
      6 => 0
      7 => 0
    ]
  ]
  #changes: []
  #casts: []
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: []
  #touches: []
  +timestamps: true
  #visible: []
  #guarded: array:1 [
    0 => "*"
  ]
  #rememberTokenName: "remember_token"
}

это то, что я пытаюсь сделать

public static function DeleteAccount($id){
    $user = User::find($id);
    $user->delete();
    return $user;
}

но это удаляет весь документ (учетную запись). Итак, как решить эту проблему?

Ответы [ 2 ]

2 голосов
/ 06 августа 2020

Отменить все из них, кроме требуемого,

public static function DeleteAccount($id){
    $user = User::find($id);
    $req = ['_id','created_at','updated_at'];
    foreach($user->toArray() as $key => $value){
        // not removing _id,created_at and updated_at
        if(!in_array($key,$req)){
            $user->unset([$key]);
        } 
    }
    $user->save();
    dd($user); //will now have only _id,created_at and updated_at
}


Примечание : мы не можем использовать здесь unset ($ user [$ key]) как он будет отключен в объекте, но, поскольку вы используете mongodb, он не будет удален в коллекции.

1 голос
/ 06 августа 2020

Учитывая вышеупомянутый документ как массив PHP от Eloquent, вы можете отключить его с помощью foreach l oop:

$document = [
  '_id' => '5cacb53ac6f0fc55aa6a2753',
  "name" => "there",
  "email" => "Nice to have you as a Guest",
  "role" => "Guest",
  // etc
  "updated_at" => "2019-04-09T15:08:09.000Z",
  "created_at" => "2019-04-09T15:07:38.000Z",
];
  
$keepFields = ['_id', 'created_at', 'updated_at'];

// Iterate through document entries
foreach ($document as $entry) {
  // If key is not in $keepFields array unset it
  if (!in_array($entry, $keepFields)) {
    unset($document[$entry]);
  }
}

dd($document);

Ваш документ выглядит как объект JavaScript. Я предполагаю, что он поступает из mon go db через Eloquent ORM на ваш контроллер в виде массива PHP.

...