【问题标题】:how to retrieve data from mongo db in lumen如何在流明中从 mongo db 中检索数据
【发布时间】:2021-05-20 08:40:31
【问题描述】:

我有一个使用 mongo db 的 lumen 项目,现在我想访问数据并对它们执行一些逻辑,我在 mongo 中的对象如下所示:

    _id: ObjectId('602cfb30bc865100073f0e56'),
    serviceType: 'normal',
    segment: 'Basic',
    steps: {
        'step1': 1,
        'step2': 2
    }

现在在我的 laravel 应用程序中我会这样做:

      $data = DiscountRule::first();
        dd($data);

结果如下:

 App\Models\Rule\DiscountRule {#183
  #collection: "discountRules"
  #connection: "mongodb"
  #dispatchesEvents: array:2 [
    "saved" => "App\Utility\Mongo\Listeners\ModelSaved"
    "deleted" => "App\Utility\Mongo\Listeners\ModelDeleted"
  ]
  -events: []
  #primaryKey: "_id"
  #keyType: "string"
  #parentRelation: null
  #table: "discountRules"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #attributes: array:4 [
    "_id" => MongoDB\BSON\ObjectId {#150
      +"oid": "602cfb30bc865100073f0e56"
    }
    "serviceType" => "pishropost-regular"
    "segment" => "Basic"
    "steps" => array:2 [
      "itemCount > 0 and itemCount <= 9" => 60000
      "itemCount > 9" => 0
    ]
  ]
  #original: array:4 [
    "_id" => MongoDB\BSON\ObjectId {#150}
    "serviceType" => "pishropost-regular"
    "segment" => "Basic"
    "steps" => array:2 [
      "itemCount > 0 and itemCount <= 9" => 60000
      "itemCount > 9" => 0
    ]
  ]
  #changes: []
  #casts: []
  #dates: []
  #dateFormat: null
  #appends: []
  #observables: []
  #relations: []
  #touches: []
  +timestamps: true
  #hidden: []
  #visible: []
  #fillable: []
  #guarded: array:1 [
    0 => "*"
  ]
}

现在它以array 的形式返回数据,但我想以对象的形式返回,这样我就可以使用$data-&gt;segment 并获取段中的数据。知道如何从 mongo 作为对象返回数据吗?

【问题讨论】:

    标签: laravel mongodb lumen


    【解决方案1】:

    如您的dd() 的第一行所述。返回的类型是App\Models\Rule\DiscountRule。所有底层数组,是 Laravel 模型在内部使用设置属性的方式。

    所以你应该可以做到。

    $rule = DiscountRule::first();
    dd($rule->segment);
    

    【讨论】:

    • 我不知道发生了什么,但我没有愚蠢地尝试过 -> 在从 get 切换到 first () 之后以任何方式感谢 :D
    猜你喜欢
    • 1970-01-01
    • 2018-12-31
    • 2019-01-06
    • 1970-01-01
    • 1970-01-01
    • 2013-06-16
    • 2011-04-12
    • 2012-04-13
    • 2016-04-04
    相关资源
    最近更新 更多