取消设置 Laravel 中除已知字段之外的所有字段?

Posted

技术标签:

【中文标题】取消设置 Laravel 中除已知字段之外的所有字段?【英文标题】:Unset all fields except a known field(s) in Laravel? 【发布时间】:2020-11-26 07:51:48 【问题描述】:

我想取消设置文档的所有字段,除了已知的一个,例如在给定的文档中我只想保留三个字段,例如

_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
]

一个文档可能比上面给出的文档有更多的字段,简而言之,我不知道文档有什么或多少个字段。

这是我在 find($id) 之后得到的数据 dd($user)

^ 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;

但这会删除一个完整的文档(帐户)。 那么如何解决这个问题呢?

【问题讨论】:

【参考方案1】:

除您需要的以外,取消所有设置,

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 时,它不会在 收藏。

【讨论】:

你测试了吗?因为它没有产生预期的结果。 我之前在mongodb lumen中使用过unset,但是上面的代码是类似的。有什么问题 取消设置后,我得到的所有字段都相同。 编辑并改进了答案,toArray() 不见了,这次试试肯定行 它工作正常。谢谢,但密码字段仍然存在,怎么办才能将其也删除?【参考方案2】:

鉴于上述文档是来自 Eloquent 的 php 数组,您可以使用 foreach 循环取消设置:

$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 对象。我假设它通过 Eloquent ORM 从 mongo db 到你的控制器作为 PHP 数组。

【讨论】:

即使在未设置之后,我也得到了具有相同字段的相同对象/数组,因此不要使用此代码。 这里不是 $entry 值,因为我知道 unset 将键作为索引

以上是关于取消设置 Laravel 中除已知字段之外的所有字段?的主要内容,如果未能解决你的问题,请参考以下文章

更新 Access 2013 中除标识列之外的所有行

如何清除霓虹灯中除第一个非零车道之外的所有车道?

选择向量中除一个之外的所有元素

删除 MySQL 中除 One 之外的所有重复行? [复制]

如何删除 Core Data 存储中除一个对象之外的所有对象?

删除 VIM 中除第一列之外的所有内容