我有一个收藏页面,页面上有很多小部件。
页面收藏 :
_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什么查询,我可以使用。
你可以使用 管道中的$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',
]
]
]);
});
}