我有收藏页面,并且页面上有许多小部件:
页面集合:
_id
name
slug,
widget_codes
小工具集合:
_id
name
code
type
product_ids
category_ids
产品集合:
_id
name
type
类别集合:
_id
name
type
我这样检索数据:
public function getData($page) {
return $page->raw(function ($collection) use ($page) {
return $collection->aggregate([
[
'$lookup' => [
'from' => 'widgets',
'localField' => 'widget_codes',
'foreignField' => 'code',
'as' => 'widgets',
]
],
[
'$match' => ['slug' => $page->slug]
]
]);
});
}
它非常完美,现在可以获取小部件数据,我想使用该小部件具有product_ids和category_ids的小部件来获取产品和类别数据。
答案 0 :(得分:0)
您可以使用pipeline in $lookup对多个表进行子查询
public function getData($page) {
return $page->raw(function ($collection) use ($page) {
return $collection->aggregate([
[
'$match' => ['slug' => $page->slug]
],
[
'$lookup' => [
'from' => 'widgets',
"let"=> [ "widget_codes"=> "$widget_codes" ],
"pipeline"=> [
[ "$match"=> [ "$expr"=> [ "$in"=> ["$_id", "$$widget_codes"] ]]],
[
'$lookup' => [
'from' => 'category',
'localField' => 'category_ids',
'foreignField' => '_id',
'as' => 'categories',
]
],
[
'$lookup' => [
'from' => 'product',
'localField' => 'product_ids',
'foreignField' => '_id',
'as' => 'products',
]
]
],
'as' => 'widgets',
]
]
]);
});
}