gpt4 book ai didi

laravel - 在 jenssegers/laravel-mongodb 中使用 where

转载 作者:行者123 更新时间:2023-12-03 19:08:52 24 4
gpt4 key购买 nike

我正在使用 jenssegers/laravel-mongodb在 Laravel 中:
我在mongodb中的数据结构如下。假设有 100 行像这样
click show image
我需要一个查询来向我显示 finance.selling_type 的所有数据状态为 1
我写代码的尝试

finances::where('finance.selling_types.$$status', 1)->get();
或者
finances::where('finance.selling_types.*.status', 1)->get();

最佳答案

使用 aggregation pipeline .
将 sell_types 中嵌入的对象转换为数组

 $convertSellingTypesToArray = [
'$project' => [
'finance.selling_types' => [
'$objectToArray' => '$finance.selling_types'
]
]
];
然后将数组展开到单个文档
$sellingTypesAsDocuments =   [
'$unwind' => '$finance.selling_types'
];
过滤状态为 1 的情况。
$selectOnlyActiveStatus = [
'$match' => [
'finance.selling_types.v.status' => [
'$eq' => 1
]
]
];
将 sell_types 转换回对象。
$convertSellingTypesToObject = [
'$project' => [
'finance.selling_types' => [
'$arrayToObject' => [
[
'$finance.selling_types'
],
]
]
]
];
finances::raw()->aggregate([
$convertSellingTypesToArray,
$sellingTypesAsDocuments,
$selectOnlyActiveStatus,
$convertSellingTypesToObject,
])

Note that you'll need to support pagination on the query

关于laravel - 在 jenssegers/laravel-mongodb 中使用 where,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62888852/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com