php Laravel / Mongodb -从多个集合获取数据

iyfjxgzm  于 2023-02-11  发布在  PHP
关注(0)|答案(2)|浏览(186)

我正在为我的Laravel应用程序使用this包。我可以使用以下查询获取单个集合数据:

$product = DB::connection( 'mongodb' )->collection( 'products_1' )->paginate( 5 );

现在,我有多个集合,例如:
产品_2、产品_3、产品_4等等...

我想一次从所有集合中获取数据。

你能告诉我有什么办法能让我得到吗?
谢谢你。

ruoxqz4g

ruoxqz4g1#

首先,创建一个Product模型:

use Jenssegers\Mongodb\Eloquent\Model;

class Product extends Model
{
    protected $collection = 'products_1';
}

然后尝试在whereRaw函数中使用$unionWith聚合:

$products = Product::whereRaw(function($collection) {
    return $collection->aggregate([
        [
            '$unionWith' => [
                'coll' => 'products_2',
            ]
        ],
        [
            '$unionWith' => [
                'coll' => 'products_3',
            ]
        ],
        [
            '$unionWith' => [
                'coll' => 'products_4',
            ]
        ],
    ]);
})->paginate(5);

参考:

如果不起作用,请尝试rawtoQuery

$products = Product::raw(function($collection) {
    return $collection->aggregate([
        [
            '$unionWith' => [
                'coll' => 'products_2',
            ]
        ],
        [
            '$unionWith' => [
                'coll' => 'products_3',
            ]
        ],
        [
            '$unionWith' => [
                'coll' => 'products_4',
            ]
        ],
    ]);
})->toQuery()->paginate(5);

参考:https://github.com/jenssegers/laravel-mongodb/issues/1574

mspsb9vt

mspsb9vt2#

我觉得最好的方法是定义集合的模型,因为关系数据库使用表,而像mongo这样的非关系数据库使用集合,我建议您在模型类中定义mongo集合。
就像普通模型一样,MongoDB模型类会根据模型名称知道使用哪个集合,对于Products,将使用集合Products。

use Jenssegers\Mongodb\Eloquent\Model;

class Book extends Model
{
    protected $collection = 'products';
}

相关问题