我有一个使用 mongo db 的 lumen 项目,现在我想访问数据并对它们做一些逻辑,我在 mongo 中的对象如下所示:
_id: ObjectId('602cfb30bc865100073f0e56'),
serviceType: 'normal',
segment: 'Basic',
steps: {
'step1': 1,
'step2': 2
}
nnow 在我的 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->segment
并获取段中的数据。知道如何从 mongo 返回数据作为对象吗?
答案 0 :(得分:1)
如您的 dd()
的第一行所述。返回的类型是App\Models\Rule\DiscountRule
。所有底层数组都是 Laravel
模型如何在内部使用设置属性进行工作。
所以你应该可以做到。
$rule = DiscountRule::first();
dd($rule->segment);